db2 - SQL Constraint that one column value cannot be greater than another in a different table -
this isn't nice question blending business logic db structure, not decision so:
is possible define constraint infers value of 1 column (table a, column x) cannot greater value of (table b, column y) referenced via foreign key:
table_a id (primary key) x (int value) table_b a_id (foreign key table_a) y (int value)
i.e. want enforce values of y, y < l l value x table_b.a_id == table_a.id
i'm working db2.
is possible define constraint infers value of 1 column (table a, column x) cannot greater value of (table b, column y) referenced via foreign key:
no. require using select statement within check constraint, , db2 doesn't support that. if did support using select statement way, this.
alter table_b add constraint table_b_y_lt_l check (y < (select x table_a table_a.id = table_b.a_id));
the select statement return single value, because table_a.id unique. but, said, db2 doesn't support select statements in check constraints. don't think current dbms does.
workarounds
there couple of workarounds. first, write trigger. second, store column "x" in both tables, , use foreign key constraint , check constraint implement requirement.
-- since "id" unique, combination of "id" , "x" unique. -- declaring "unique (id, x)" lets these 2 columns target of -- foreign key reference. -- create table table_a ( id integer primary key, x integer not null, unique (id, x) ); -- foreign key references both columns in "table_a". check constraint -- indirectly guarantees y < table_a.x. -- create table table_b ( a_id integer not null, a_x integer not null, y integer not null, primary key (a_id, a_x, y), foreign key (a_id, a_x) references table_a (id, x), check (y < a_x) );
this standard sql. should work in current sql dbms.