Question

With Firebird, if I have a check constrained by a subquery to another table, and I write to the table in the subquery that would violate the check, what fails, if anything?

If nothing fails, will the constraint be violated on the next read from the table with the check constraint? If not, what does Firebird do to prevent the constraint from being violated on read?

Example

table_a has a check constraint on column_a_table_a that should be < SUM(column_a_table_b) FROM table_b.

Was it helpful?

Solution

A CHECK CONSTRAINT only applies to the table it is defined on, and only guarantees integrity if the constraint is derived from the row it is applied to.

This is also documented in the Interbase 6.0 Data Definition Guide on page 106 (available from the reference manual section of the Firebird site):

Note A CHECK constraint guarantees data integrity only when the values being verified are in the same row that is being inserted and deleted. If you try to compare values in different rows of the same table or in different tables, another user could later modify those values, thus invalidating the original CHECK constraint that was applied at insertion time.

So if you modify table_b in such a way that the check contraint applied to table_a no longer holds, then you will not receive an error because this constraint does not apply to this table.

Now if you modify table_a, the check constraint will fire and will result in an error (only for modified row(s), and only where the constraint no longer holds).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top