Sub topic 11
Enforcing rules with CHECK
A CHECK constraint attaches a true-or-false condition to a table. The database evaluates it for every row that is inserted or updated. If the condition is false, the statement fails and no data changes. This chapter assumes you know the NOT NULL, DEFAULT, PRIMARY KEY, and FOREIGN KEY constraints from earlier chapters. It also assumes you can read basic SQL expressions such as comparisons, AND, OR, and IN.
What CHECK does
NOT NULL, UNIQUE, and FOREIGN KEY each cover one fixed kind of rule. CHECK covers business rules that need an expression: a price cannot be negative, a discount is between 0 and 100, an end date cannot precede a start date.
The condition can use:
- comparison operators (
=,<>,<,>=) BETWEEN,IN, andLIKEAND,OR, andNOT- deterministic functions such as
UPPERandLENGTH - other columns of the same row
The examples below use PostgreSQL syntax. Differences in other systems are covered near the end.
CREATE TABLE promotions (
promo_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
code VARCHAR(20) NOT NULL,
discount_pct NUMERIC(5, 2) NOT NULL
CHECK (discount_pct BETWEEN 0 AND 100),
min_spend NUMERIC(10, 2)
CHECK (min_spend >= 0),
starts_on DATE NOT NULL,
ends_on DATE,
CONSTRAINT ck_promotions_code
CHECK (code = UPPER(code) AND LENGTH(code) >= 4),
CONSTRAINT ck_promotions_dates
CHECK (ends_on IS NULL OR ends_on >= starts_on)
);This table has four CHECK constraints:
discount_pctandmin_spendcarry column-level checks that look at one column each.ck_promotions_codeis a named table-level check on thecodecolumn.ck_promotions_datesis a named table-level check that compares two columns in the same row.
How a check is evaluated
SQL uses three-valued logic, so a condition has three possible results: TRUE, FALSE, or UNKNOWN. A comparison with NULL, such as NULL >= 0, gives UNKNOWN. The CHECK rule is easy to misremember:
The diagram shows the decision for each affected row.
In promotions, min_spend allows NULL. A row with min_spend = NULL passes CHECK (min_spend >= 0) because the result is UNKNOWN. If a value must be present and valid, pair the CHECK with NOT NULL, as discount_pct does.
The date rule uses the same idea on purpose. ends_on IS NULL OR ends_on >= starts_on makes the open-ended case explicit. Without the IS NULL branch the result would still be UNKNOWN and the row would still pass, but the explicit form shows the intent to readers.
Seeing the rejections
Run one valid insert and then several that each break a rule.
INSERT INTO promotions (code, discount_pct, min_spend, starts_on, ends_on)
VALUES ('SPRING10', 10, NULL, '2026-03-01', NULL); -- accepted: NULL min_spend yields UNKNOWN
INSERT INTO promotions (code, discount_pct, starts_on)
VALUES ('BIG', 150, '2026-03-01'); -- fails: discount_pct above 100
INSERT INTO promotions (code, discount_pct, starts_on)
VALUES ('spring', 5, '2026-03-01'); -- fails: code not uppercase
INSERT INTO promotions (code, discount_pct, starts_on, ends_on)
VALUES ('LATE', 5, '2026-03-10', '2026-03-01'); -- fails: ends before it startsA failing statement raises an error that names the table and the constraint. In PostgreSQL the last insert reports:
ERROR: new row for relation "promotions" violates check constraint "ck_promotions_dates"
DETAIL: Failing row contains (2, LATE, 5.00, null, 2026-03-10, 2026-03-01).The constraint name is the most useful part of the message. The BIG insert violates a constraint you did not name, so PostgreSQL generates a name such as promotions_discount_pct_check. Naming constraints, covered in a later chapter, makes errors like this easier to read and act on.
Column-level and table-level placement
A check on one column can sit beside that column. A check that involves two or more columns must be a table-level constraint, because it is not attached to a single column. In promotions, ck_promotions_dates is table-level for this reason.
Placement does not change behavior. PostgreSQL stores a column-level check as an ordinary table check. Choose the placement that reads best.
Multi-column rules and common patterns
| Rule | CHECK expression |
|---|---|
| Value is not negative | `CHECK (quantity >= 0)` |
| Value within a range | `CHECK (rating BETWEEN 1 AND 5)` |
| Value from a short list | `CHECK (status IN ('new', 'paid', 'shipped'))` |
| Start before end | `CHECK (ends_on >= starts_on)` |
| Exactly one of two columns set | `CHECK ((phone IS NULL) <> (email IS NULL))` |
| Minimum text length | `CHECK (LENGTH(TRIM(name)) > 0)` |
The IN list approach suits values that rarely change. If the list changes often, a lookup table with a foreign key is easier to maintain, because adding a value becomes an INSERT instead of a schema change.
Limits and gotchas
- One row only. A CHECK sees the row being written. It cannot compare against other rows or other tables. In PostgreSQL it cannot contain a subquery. Use a foreign key, a unique constraint, or a trigger for those cases.
- Avoid time-dependent conditions. A check such as
CHECK (ends_on > CURRENT_DATE)is evaluated only when the row is written. The row stays in the table after the date passes, so the rule silently stops being true. Use deterministic conditions that depend only on the row's own values. - Existing data is tested. Adding a CHECK with
ALTER TABLEvalidates all current rows, and the statement fails if any row violates the rule. Fix or remove the bad rows first. PostgreSQL also acceptsADD CONSTRAINT ... NOT VALID, which skips the existing rows and checks only new writes. - Updates are checked too. An
UPDATEthat changes a column in the condition is re-evaluated, even when the other columns are unchanged.
Dialect differences
CHECK syntax is standard SQL, but enforcement varies:
- PostgreSQL, SQL Server, and SQLite enforce CHECK constraints.
- MySQL enforces them from version 8.0.16. Older MySQL versions and MariaDB before 10.2.1 accept the syntax but ignore the rule. Test a failing insert on your server to confirm.
- Function names differ. SQL Server uses
LENwhere the examples useLENGTH. - Syntax for dropping a constraint differs across systems. A later chapter covers it.
Exercise
A table has the column rating INTEGER CHECK (rating BETWEEN 1 AND 5) and no NOT NULL constraint. Which of these inserts are accepted: rating 5, rating 0, rating NULL? Explain, and show how to reject the NULL case.
Show answer
Rating 5 is accepted because the condition is TRUE. Rating 0 is rejected because the condition is FALSE. Rating NULL is accepted because NULL BETWEEN 1 AND 5 evaluates to UNKNOWN, and CHECK rejects a row only when the condition is FALSE. To reject NULL, add NOT NULL: rating INTEGER NOT NULL CHECK (rating BETWEEN 1 AND 5).
Exercise
Write a table-level CHECK, named ck_events_capacity, for a table events with columns seats_sold and capacity. It must ensure seats_sold is never negative and never exceeds capacity.
Show answer
CONSTRAINT ck_events_capacity CHECK (seats_sold >= 0 AND seats_sold <= capacity). It must be table-level because it compares two columns. If seats_sold or capacity can be NULL, add NOT NULL to those columns, or the check passes with UNKNOWN.