← Back to SQL, page 3

sql-0044 · Medium mid

A table has CHECK (marks BETWEEN 0 AND 100). Why is a NULL mark still accepted?

A CHECK constraint rejects a row only when its condition is FALSE. For a NULL mark the condition is UNKNOWN, and UNKNOWN passes. This is the opposite of WHERE, which keeps only TRUE. Add NOT NULL if a value is required.

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;
studentmarks
Ana88
BenNULL

The NULL mark was accepted, while 120 is rejected:

sql
INSERT INTO results VALUES ('Chen', 120);  -- error on purpose
text
Error: CHECK constraint failed: marks BETWEEN 0 AND 100

This 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 purpose
text
Error: NOT NULL constraint failed: results2.marks

The 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