Can a SQLite CHECK constraint compare values in different columns?
Quick answer
Yes. A SQLite table-level CHECK can compare columns in the same row, for example CHECK (start_value <= end_value). SQLite checks the expression when a row is inserted or updated; a result of zero violates the constraint. This does not enforce rules across multiple rows. Also, a NULL result is not considered a violation, so use NOT NULL if either value must be present. [S1]
The question, the details, the next step.
A practical checklist
Write the comparison using the two column names, such as
CHECK (start_value <= end_value).Place the table-level CHECK inside the table definition.
Decide whether either value may be NULL; add NOT NULL where presence is required.
Test a less-than case, an equal case, and a greater-than case on a disposable table.
Keep cross-row rules, such as overlap checks, separate from this row-level constraint.
A few more useful answers
Does the CHECK run only when a row is first inserted?
No. SQLite evaluates CHECK expressions when rows are inserted or updated. [S1] The comparison therefore applies to the row values at either of those operations.
Does this constraint prevent two rows from having the same values?
No. The example checks the relationship between two columns within each row; it does not establish uniqueness or compare rows with each other.
Why include NOT NULL if the CHECK already compares the columns?
Because a CHECK expression that evaluates to NULL is not considered a violation. [S1] NOT NULL separately requires a value in each column.
Sources
References used for this guide.
- [S1] SQLite CREATE TABLE: CHECK constraint behavior sqlite.org · Checked
