Full answer
sql
CREATE TABLE promos (
id INTEGER PRIMARY KEY,
price INTEGER NOT NULL CONSTRAINT price_non_negative CHECK (price >= 0),
start_date TEXT NOT NULL,
end_date TEXT,
CONSTRAINT dates_in_order CHECK (end_date IS NULL OR end_date >= start_date)
);
INSERT INTO promos VALUES (1, 100, '2026-03-01', NULL), (2, 0, '2026-03-01', '2026-03-31');
SELECT * FROM promos ORDER BY id;| id | price | start_date | end_date |
|---|---|---|---|
| 1 | 100 | 2026-03-01 | NULL |
| 2 | 0 | 2026-03-01 | 2026-03-31 |
Both bad rows are rejected:
sql
CREATE TABLE p2 (price INTEGER NOT NULL CHECK (price >= 0));
INSERT INTO p2 VALUES (-5);
-- error on purposetext
Error: CHECK constraint failed: price >= 0sql
CREATE TABLE p3 (start_date TEXT NOT NULL, end_date TEXT, CONSTRAINT dates_in_order CHECK (end_date IS NULL OR end_date >= start_date));
INSERT INTO p3 VALUES ('2026-03-10', '2026-03-01');
-- error on purposetext
Error: CHECK constraint failed: dates_in_orderThe NULL rule matters: CHECK (price >= 0) lets a NULL price through, because the check evaluates to unknown, not false. That is why price is also NOT NULL here, while end_date is allowed to be NULL for open-ended promotions.
Name constraints (CONSTRAINT price_non_negative CHECK (...)) so error messages and later migrations are clear.
sql
CREATE TABLE promos (
id INTEGER PRIMARY KEY,
price INTEGER NOT NULL CONSTRAINT price_non_negative CHECK (price >= 0),
start_date TEXT NOT NULL,
end_date TEXT,
CONSTRAINT dates_in_order CHECK (end_date IS NULL OR end_date >= start_date)
);
INSERT INTO promos VALUES (1, 100, '2026-03-01', NULL), (2, 0, '2026-03-01', '2026-03-31');
SELECT * FROM promos ORDER BY id;
-- error on purpose
CREATE TABLE p2 (price INTEGER NOT NULL CHECK (price >= 0));
INSERT INTO p2 VALUES (-5);
-- error on purpose
CREATE TABLE p3 (start_date TEXT NOT NULL, end_date TEXT, CONSTRAINT dates_in_order CHECK (end_date IS NULL OR end_date >= start_date));
INSERT INTO p3 VALUES ('2026-03-10', '2026-03-01');Checked on SQLite 3.46.1, run twice with identical output.
Key points
- CHECK enforces a rule per row
- Table-level CHECKs can compare columns
- NULL makes a CHECK pass; combine with NOT NULL
- Name constraints for clearer errors
Common mistakes
- Assuming CHECK rejects NULLs
- Enforcing simple row rules only in application code
Follow-ups
- Can a CHECK refer to other rows or tables?
- How would you add a CHECK to an existing table with bad data?
Tips
- Mention the NULL pass-through