← Back to SQL, page 9

sql-0178 · Easy fresher

Write a table definition that rejects negative prices and an end date before the start date.

Use CHECK constraints: CHECK (price >= 0) on the column and a table-level CHECK (end_date IS NULL OR end_date >= start_date). A CHECK passes when the expression is true or NULL, so add NOT NULL where a value is required.

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;
idpricestart_dateend_date
11002026-03-01NULL
202026-03-012026-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 purpose
text
Error: CHECK constraint failed: price >= 0
sql
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 purpose
text
Error: CHECK constraint failed: dates_in_order

The 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