Let’s say I have the following two postgres tables with the same field:
CREATE TABLE table1 (
label VARCHAR(50)
);
CREATE TABLE table2 (
label VARCHAR(50)
);
I want label
to be unique across both tables. That is, the following data should raise an error:
INSERT INTO table1 (label) VALUES ('hello');
INSERT INTO table2 (label) VALUES ('hello');
Is there any way to enforce this at the database level?
2
Answers
You cannot create a unique constraint across table, but a trigger on both tables can. One way: (see demo)
This is an example where a third table and some rules could be very beneficial:
This also works when you have concurrent inserts on both tables, even when you have long running transactions.
This would be one of the very few exceptions where I would recommend the usage of a RULE.