Full answer
WHERE and CHECK treat UNKNOWN in opposite ways:
- WHERE keeps a row only if the condition is TRUE.
- CHECK rejects a row only if the condition is FALSE.
So a CHECK constraint lets UNKNOWN through, and any comparison involving NULL is UNKNOWN.
sql
CREATE TABLE results (student TEXT, marks INTEGER CHECK (marks BETWEEN 0 AND 100));
INSERT INTO results VALUES ('Ana', 88), ('Ben', NULL);
SELECT student, marks FROM results ORDER BY student;| student | marks |
|---|---|
| Ana | 88 |
| Ben | NULL |
The NULL mark was accepted, while 120 is rejected:
sql
INSERT INTO results VALUES ('Chen', 120); -- error on purposetext
Error: CHECK constraint failed: marks BETWEEN 0 AND 100This is the intended design: CHECK validates values that exist, and NOT NULL is the separate tool that says a value must exist. Combine them when both rules apply:
sql
CREATE TABLE results2 (student TEXT, marks INTEGER NOT NULL CHECK (marks BETWEEN 0 AND 100));
INSERT INTO results2 VALUES ('Ana', 88);
SELECT COUNT(*) AS accepted FROM results2;| accepted |
|---|
| 1 |
sql
INSERT INTO results2 VALUES ('Ben', NULL); -- error on purposetext
Error: NOT NULL constraint failed: results2.marksThe same reasoning applies to multi-column checks such as CHECK (end_date > start_date). A row with no end date passes, which is often correct (the course has not ended yet), but it should be a decision, not an accident.
sql
CREATE TABLE results (student TEXT, marks INTEGER CHECK (marks BETWEEN 0 AND 100));
INSERT INTO results VALUES ('Ana', 88), ('Ben', NULL);
SELECT student, marks FROM results ORDER BY student;
-- error on purpose
INSERT INTO results VALUES ('Chen', 120);
CREATE TABLE results2 (student TEXT, marks INTEGER NOT NULL CHECK (marks BETWEEN 0 AND 100));
INSERT INTO results2 VALUES ('Ana', 88);
SELECT COUNT(*) AS accepted FROM results2;
-- error on purpose
INSERT INTO results2 VALUES ('Ben', NULL);Checked on SQLite 3.46.1, run twice with identical output.
Key points
- CHECK fails only on FALSE; UNKNOWN passes
- WHERE keeps only TRUE; the two are opposites
- Add NOT NULL when a value must be present
- Multi-column checks also pass when any column is NULL
Common mistakes
- Relying on CHECK to require a value
- Writing CHECK (col IS NOT NULL AND ...) everywhere instead of declaring NOT NULL
Follow-ups
- How would you require end_date to be after start_date only when it is present?
- Does a FOREIGN KEY accept NULL?
Tips
- State the WHERE versus CHECK contrast in one sentence