Sub topic 4
Constraints that keep the data honest
This chapter assumes you can write basic SELECT, INSERT, and UPDATE statements, and that you have PostgreSQL 12 or newer and a psql session open. It also assumes you have created the authors, books, and readings tables from the earlier chapters. The definitions are repeated here where they matter.
A constraint is a rule the database enforces on every write. Application code can have bugs, and scripts and one-off psql sessions skip the application entirely. A constraint holds in all of those cases, because the check happens inside PostgreSQL.
How a write meets the constraints
When you insert or update a row, PostgreSQL tests it against each constraint. If any test fails, the whole statement is rolled back and you get an error with a five-character SQLSTATE code.
Foreign keys are the subject of the next chapter. This chapter covers the first three checks.
NOT NULL
NOT NULL forbids the missing-value marker NULL in a column. Our books.title and authors.name columns have it, so a book without a title cannot exist.
INSERT INTO books (title, isbn13) VALUES (NULL, '9780000000003');ERROR: null value in column "title" of relation "books" violates not-null constraintNOT NULL only blocks NULL. An empty string '' is a real value and passes. We deal with that under CHECK.
UNIQUE
UNIQUE guarantees that no two rows share the same value in the column. We put it on isbn13 because an ISBN identifies one edition of a book. PostgreSQL enforces it with a unique index, which it creates automatically.
INSERT INTO books (title, isbn13) VALUES ('Constraint Demo', '9780000000010');
INSERT INTO books (title, isbn13) VALUES ('Constraint Demo Again', '9780000000010');ERROR: duplicate key value violates unique constraint "books_isbn13_key"
DETAIL: Key (isbn13)=(9780000000010) already exists.NULL is never equal to another NULL, so a plain UNIQUE column accepts any number of NULL values. Two books with no ISBN are both allowed. This suits older books that predate ISBNs. If you want at most one NULL, PostgreSQL 15 and newer support UNIQUE NULLS NOT DISTINCT.
CHECK
A CHECK constraint holds a boolean expression that every row must satisfy. The books table uses three:
CREATE TABLE books (
book_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
isbn13 char(13) UNIQUE CHECK (isbn13 ~ '^[0-9]{13}$'),
published_year smallint CHECK (published_year BETWEEN 1400 AND 2100),
page_count integer CHECK (page_count > 0)
);The ~ operator tests a regular expression. '^[0-9]{13}$' means exactly thirteen digits and nothing else. A value like '978-0-00' is rejected even though it fits in char(13).
INSERT INTO books (title, page_count) VALUES ('Zero Pages', 0);ERROR: new row for relation "books" violates check constraint "books_page_count_check"CHECK passes on NULL
A CHECK rejects a row only when the expression is false. When the expression is NULL, the row passes. With page_count set to NULL, page_count > 0 evaluates to NULL, so this insert succeeds:
INSERT INTO books (title, page_count) VALUES ('Unknown Length', NULL);To require a value, combine the rules: page_count integer NOT NULL CHECK (page_count > 0). Use NOT NULL to say a value must exist and CHECK to say what it may be.
Blocking blank titles
Because '' passes NOT NULL, add a check that rejects empty and whitespace-only titles:
ALTER TABLE books
ADD CONSTRAINT books_title_not_blank CHECK (length(btrim(title)) > 0);This statement scans the table and fails if any existing row breaks the rule. That matters on a table that already holds data, as the section on existing data explains.
Constraints that span columns
A column constraint looks at one column. A table-level CHECK can compare several columns in the same row. The readings table uses two:
CREATE TYPE reading_status AS ENUM ('want_to_read', 'reading', 'finished', 'abandoned');
CREATE TABLE readings (
reading_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
book_id bigint NOT NULL REFERENCES books (book_id),
status reading_status NOT NULL DEFAULT 'want_to_read',
started_on date,
finished_on date,
rating smallint CHECK (rating BETWEEN 1 AND 5),
CHECK (finished_on IS NULL OR started_on IS NULL OR finished_on >= started_on),
CHECK (rating IS NULL OR status = 'finished')
);The first check says a book cannot be finished before it was started. The IS NULL branches are optional here, since NULL >= date already yields NULL and passes. They state the intent: skip the comparison when a date is unknown.
The second check needs its IS NULL branch. Without it, status = 'finished' would be false for every unfinished book, and no unrated unfinished reading could be saved. With it, a rating is allowed only on a finished reading:
INSERT INTO readings (book_id, status, rating)
SELECT book_id, 'reading', 5
FROM books
WHERE isbn13 = '9780000000010';ERROR: new row for relation "readings" violates check constraint "readings_check1"PostgreSQL names unnamed table-level checks readings_check, readings_check1, and so on. Those names tell you nothing, which is the reason to name constraints yourself.
Naming constraints and reading the error
Column constraints get generated names such as books_isbn13_key and books_page_count_check. List what a table has with the system catalog:
SELECT conname, contype, pg_get_constraintdef(oid) AS definition
FROM pg_constraint
WHERE conrelid = 'books'::regclass
ORDER BY conname;contype is p for primary key, u for unique, c for check, and f for foreign key. On PostgreSQL 17 and older, NOT NULL does not appear in this list. Version 18 adds it.
Give constraints a name with CONSTRAINT name so errors are readable and you can drop them later:
ALTER TABLE books
ADD CONSTRAINT books_page_count_positive CHECK (page_count > 0);Application code can react to the SQLSTATE code instead of parsing message text:
| SQLSTATE | Condition name | Cause |
|---|---|---|
| 23502 | not_null_violation | `NULL` in a `NOT NULL` column |
| 23505 | unique_violation | Duplicate value in a unique column |
| 23514 | check_violation | A `CHECK` expression was false |
| 23503 | foreign_key_violation | Referenced row missing, or still referenced |
Adding constraints to existing data
Adding a constraint to a populated table validates every row first. If one row is bad, the whole ALTER TABLE fails. On a large table it also holds a strong lock while it scans.
You can split the work in two. NOT VALID enforces the rule on new writes immediately but skips the scan of old rows. VALIDATE CONSTRAINT checks old rows later under a weaker lock that still lets normal reads and writes continue:
ALTER TABLE books
ADD CONSTRAINT books_year_plausible
CHECK (published_year BETWEEN 1400 AND 2100) NOT VALID;
-- Fix any offending rows here, then:
ALTER TABLE books VALIDATE CONSTRAINT books_year_plausible;Common errors and limits
- Expecting
CHECKto rejectNULL. It does not. AddNOT NULL. - Expecting
UNIQUEto reject repeatedNULLs. It does not, unless you useNULLS NOT DISTINCTon PostgreSQL 15 or newer. - Putting a changing value in a
CHECK. A rule likepublished_year <= extract(year FROM now())gives different answers over time. Old rows can then violate it, and restoring a dump can fail. Keep checks to rules that depend only on the row. Use a trigger when you need time-dependent logic. - Referring to other tables in a
CHECK. PostgreSQL does not allow subqueries there. Use a foreign key for existence rules and a unique constraint for uniqueness rules. - Treating the application as the only guard. Validation in code gives friendly messages, but only constraints cover every writer.
Exercise
A readings row has status = 'finished', started_on = '2026-03-10', and finished_on = NULL. Does the date check CHECK (finished_on IS NULL OR started_on IS NULL OR finished_on >= started_on) accept it? Which SQLSTATE would you see if it did not?
Show answer
It accepts the row. finished_on IS NULL is true, so the whole OR expression is true. A rejection would raise SQLSTATE 23514 (check_violation).
Exercise
You run INSERT INTO books (title, isbn13) VALUES ('Draft A', NULL), ('Draft B', NULL); on the books table above. Does it succeed? Write a single ALTER TABLE that would make the second row fail on PostgreSQL 15 or newer.
Show answer
It succeeds, because UNIQUE treats each NULL as distinct. To forbid more than one NULL, drop books_isbn13_key and add ALTER TABLE books ADD CONSTRAINT books_isbn13_key UNIQUE NULLS NOT DISTINCT (isbn13);. The second NULL row then raises SQLSTATE 23505.