Using postgresql 9.5, assume I have a table:
CREATE TABLE t (
id INT,
primary TEXT,
secondary TEXT
)
I want to guarantee that the union of values in primary
and secondary
does not contain duplicates. Is this doable via index/checks or do I have to go to a trigger?
For example,
INSERT INTO t(id, primary, secondary) VALUES(1, 'a', 'b');
INSERT INTO t(id, primary, secondary) VALUES(1, 'x', 'y');
INSERT INTO t(id, primary, secondary) VALUES(1, 'a', 'z');
INSERT INTO t(id, primary, secondary) VALUES(1, 'z', 'a');
The latter two INSERTs should fail.
Best Answer
A trigger solution might work but I'd prefer to normalize the design and have simple constraints:
The table that is now:
would become:
Then your inserts
would become:
Finally you can have the original output with: