Can I create a constraint on a database that ensures some relationship between columns in different tables linked by a foreign key? So, as an example, can I ensure that a row in a table has a value for a certain column that is larger than the value in a column in a row in another table that it references.
So naively you might think it would look like:
CREATE table1 (
id integer PRIMARY KEY,
col1 integer
);
CREATE table2 (
id integer PRIMARY KEY,
link_to_1 integer REFERENCES table1,
col2 integer,
-- Is there some way of specifying the following constraint?
CHECK (col2 > link_to_1.col1)
);
So a row in table1
can never have an entry with a col1 greater than the col2
value in the link_to_1
row.
Obviously this constraint would therefore prevent you from subsequently modifying the table1.col1
value to be a higher value than the table2.col2
value.