CHECK Constraints & Limits in SQL
Cheapest invariant — with a NULL loophole to close
CHECK enforces row predicates (salary >= 0, end > start) — rejected writes fail fast. Limits: no subqueries or cross-table refs (use triggers/deferred constraints), NULL passes (UNKNOWN is not FALSE — pair with NOT NULL), complex rules live in app validation plus the constraint as backstop. Every column-local rule belongs here.
Row-local rules
salary >= 0, end > start — evaluated on INSERT/UPDATE, fail fast with named errors.
Span two columns
CONSTRAINT valid_range CHECK (end_time > start_time) — intra-row, not cross-table.
Know the walls
No subqueries/cross-table refs; NULL passes; complex belongs in app + trigger + constraint backstop.
Name + add safely
Named constraints greppable; dirty tables need clean/quarantine + NOT VALID/VALIDATE.
1CREATE TABLE staff (id INT PRIMARY KEY, salary NUMERIC CHECK (salary >= 0));2INSERT INTO staff VALUES (1, -5); -- rejected
| error |
|---|
| ERROR: new row violates check constraint "staff_salary_check" |
Negative salary fails regardless of which app, script or intern sent it. NULL salary would still pass — the nullable-column loophole to close with NOT NULL.
Negative rejected everywhere
Engine refuses regardless of writer.
1INSERT INTO staff (id, email, salary) VALUES (1, 'a@x.com', -5);
| error |
|---|
| ERROR: new row violates check constraint "staff_salary_check" |
Two-column range
End must exceed start on the same row.
1CONSTRAINT valid_range CHECK (end_time > start_time)
| case | verdict |
|---|---|
| valid | end after start |
| invalid | rejected at write |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.