I have a table with a timestamp field onto which I’ve created a composite index.
CREATE INDEX "IDX_NAME_A" ON TABLE "A" (a_id, extract(year FROM created_at))
I have another table which stores a year and a_id which I’d like to have a foreign key relation.
I can’t seem to find the syntax to do what I want.
ALTER TABLE "B"
ADD FOREIGN KEY(a_id, a_year)
REFERENCES A(a_id, extract(YEAR FROM created_at));
produces:
ERROR: syntax error at or near "("
I’ve also tried …
ALTER TABLE "B"
ADD FOREIGN KEY(a_id, a_year)
USING INDEX "IDX_NAME_A";
Any Ideas?
Table A
--------
a_id serial,
created_at timestamp default now()
Table B
-------
b_id serial
a_id integer not null,
a_year date_part('year')
A foreign key constraint cannot reference an index. It has to be a table.
A foreign key constraint cannot reference an expression. It has to point to column name(s) of the referenced table.
And there has to exist a unique index (primary key qualifies, too, implicitly) on the set of referenced columns.
Start by reading the manual about foreign keys here.
The superior design would be to just drop the column
b.a_year. It is 100% redundant and can be derived froma.created_atany time.If you positively need the column (for instance to enforce one row per year for certain criteria in table
b), you can achieve your goal like this:Updated after @Catcall’s comment:
The
CHECKconstraint in combination with the columnDEFAULTandNOT NULLclauses enforces your regime.Alternatively (less simple, but allowing for
NULLvalues) you could maintain the values ina.a_yearwith a trigger: