Lesson 13 of 29Designing schemas
Constraints: Let the Database Say No
Use NOT NULL, UNIQUE, CHECK, foreign keys, deferrable and exclusion constraints so bad data cannot get in, and turn violations into clean API errors.
A support ticket arrives: one customer has two accounts with the same email, and password resets go to the wrong one. The sign-up code checks for an existing email before inserting, and it has unit tests. It still failed, because two requests arrived in the same few milliseconds on two different app servers. Every team hits some version of this bug. The fix is not more careful application code. It is a rule the database enforces on every write, from every service, for the life of the table. This lesson covers the constraints you will use at work, how each behaves underneath, and how to turn their errors into good API responses.
Why the application check is not enough
The tempting pattern is check-then-insert: SELECT to see whether the email exists, and INSERT if it does not. On one server with one request at a time, that works. In production you have several app servers, each handling many requests at once, and nothing stops two of them from running their SELECT before either runs its INSERT.
Server A checks whether the email is taken.
Here is the same interleaving with two real connections to one database file. The first table has no rule; the second has UNIQUE.
Press Run (⌘ Enter) to see what happens.Wrapping the check and the insert in a transaction does not fix this on its own. In Postgres's default isolation level, both transactions still see "no rows" and both insert. A unique index works because it is a single shared structure: the second insert has to look at the same index entry the first one just wrote, and it waits for or conflicts with it. The later lessons on isolation and locking show the full picture. For now, the rule is: anything that must always be true goes in a constraint. Keep the application check too, for a friendly message on the common path, but treat it as UX, not as protection.
Constraints also protect you from the writes nobody thinks about: a backfill script, a second service that shares the table, an engineer fixing data by hand at 2 a.m., and an ORM bug that skips your validation layer.
The everyday constraints
You met primary keys, foreign keys, NOT NULL and CHECK in Tables, Rows and the Relational Model. Here is how each one behaves in detail.
NOT NULLis the cheapest and most valuable. Make every columnNOT NULLunless "unknown" is a real state you will handle. Adding it later to a big table is much harder than starting with it.DEFAULTis not a constraint, but it pairs withNOT NULL:created_at timestamptz NOT NULL DEFAULT now()means callers cannot forget it.CHECK (expression)rejects a row when the expression is false. It can compare several columns of the same row, such asends_on > starts_on. It cannot look at other rows or other tables; that needs a constraint type built for it, or a trigger.UNIQUEcan span several columns.UNIQUE (store_id, code)lets two stores both have aSPRINGcoupon but stops one store having two.PRIMARY KEYisUNIQUEplusNOT NULL, one per table.
Name your constraints. The name appears in every error message, you need it to drop or alter the constraint, and your app code can match on it. Postgres generates names like coupons_check1 if you do not, which tell nobody anything.
Press Run (⌘ Enter) to see what happens.Look at the last attempt. A CHECK fails only when its expression is false. When it is NULL (unknown), the row passes. CHECK (ends_on > starts_on) would have let a NULL ends_on through anyway, which is why the explicit ends_on IS NULL OR ... is clearer. If you do not want NULLs, say NOT NULL separately.
UNIQUE and NULL
Two NULLs are not equal to each other, so by default a UNIQUE column accepts any number of NULLs. That matches the standard and Postgres, MySQL and SQLite all behave this way. SQL Server is the exception: its unique constraints allow only one NULL.
Press Run (⌘ Enter) to see what happens.Usually that is what you want. When it is not, for example "at most one default address per customer, where label may be NULL", Postgres 15 and later accept UNIQUE NULLS NOT DISTINCT (customer_id, label). The other common variant is a partial unique index: CREATE UNIQUE INDEX ... WHERE deleted_at IS NULL enforces uniqueness only among live rows. Composite, Covering and Partial Indexes runs that pattern for soft-deleted users.
Foreign keys and what happens on delete
A foreign key says "this value must exist as a key in that table". The interesting decision is what happens when someone deletes or changes the parent row. You choose per foreign key:
| Action | Deleting the parent... | Typical use |
|---|---|---|
NO ACTION (default) | fails if children exist; checked at the end of the statement | most relationships |
RESTRICT | fails if children exist; checked immediately, cannot be deferred | the same, stated loudly |
CASCADE | deletes the children too | rows that cannot exist alone: order lines, a post's comments |
SET NULL | sets the child's column to NULL | optional links: a comment whose author left |
SET DEFAULT | sets the child's column to its default | rare |
Press Run (⌘ Enter) to see what happens.Deleting Ada removed her post, the cascade removed comment 100 on that post, and her comment on Grace's post stayed with its author set to NULL. Deleting Grace failed because an invoice points at her, and invoices are records you must keep.
Two cautions that seniors raise in review. First, CASCADE is powerful and quiet. One DELETE FROM customers WHERE id = 5 can remove thousands of rows across several tables, and nothing in the statement says so. Use it where the children truly belong to the parent, and prefer RESTRICT plus soft deletes for business records. Second, index the foreign key column. Postgres creates an index for a primary key or UNIQUE constraint, but not for the referencing side. Without CREATE INDEX ON orders (customer_id), every delete of a customer scans the whole orders table to look for children, while holding locks. That is a classic cause of a "simple" admin delete timing out.
SQLite: enforcement is opt-in, per connection
You saw that SQLite ignores foreign keys unless each connection runs PRAGMA foreign_keys = ON. There are two more traps. The pragma does nothing inside an open transaction, and Python's sqlite3 module quietly opens one before an INSERT. And turning enforcement on does not check the rows already there.
Press Run (⌘ Enter) to see what happens.Set the pragma straight after connecting, before anything else, which is what shopdb.connect() does. If a SQLite database has lived without it, run PRAGMA foreign_key_check to find the orphans before you rely on the keys.
Deferrable constraints
Normally a constraint is checked as each statement runs. Some valid changes pass through an invalid state on the way. A deferrable constraint can wait until COMMIT.
The classic case is a cycle: every team has a lead, and every lead belongs to a team. Whichever row you insert first points at something that does not exist yet. SQLite supports deferred foreign keys, so you can run it:
Press Run (⌘ Enter) to see what happens.The second case is renumbering. Shifting every position up by one in a table with UNIQUE (position) collides with the next row partway through:
Press Run (⌘ Enter) to see what happens.Postgres fails the same way, because a non-deferrable UNIQUE is checked row by row. Declaring it deferrable moves the check to the end of the statement, or to COMMIT if you ask:
ALTER TABLE playlist
ADD CONSTRAINT playlist_position_key UNIQUE (position)
DEFERRABLE INITIALLY IMMEDIATE;
UPDATE playlist SET position = position + 1; -- now works: checked after the statement
BEGIN;
SET CONSTRAINTS playlist_position_key DEFERRED; -- wait until COMMIT
UPDATE playlist SET position = 2 WHERE song = 'Intro';
UPDATE playlist SET position = 1 WHERE song = 'Verse';
COMMIT;In Postgres, UNIQUE, PRIMARY KEY, foreign key and exclusion constraints can be deferrable; NOT NULL and CHECK cannot. Deferrable unique constraints have costs: INSERT ... ON CONFLICT cannot use one as its arbiter, and a foreign key cannot reference one. So use deferral where you need it, not by default.
Rules across rows: exclusion constraints
UNIQUE says "no two rows are equal". Some rules say "no two rows overlap": a meeting room cannot have two bookings at the same time, and a product cannot have two prices active on the same day. A CHECK cannot see other rows, and an application check has the same race as the sign-up bug. Postgres has a constraint for exactly this:
CREATE EXTENSION IF NOT EXISTS btree_gist; -- lets GiST handle plain = on room_id
CREATE TABLE room_bookings (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
room_id bigint NOT NULL REFERENCES rooms (id),
during tstzrange NOT NULL,
CONSTRAINT room_bookings_no_overlap
EXCLUDE USING gist (room_id WITH =, during WITH &&)
);
INSERT INTO room_bookings (room_id, during) VALUES (1, '[2026-03-02 09:00, 2026-03-02 10:00)');
INSERT INTO room_bookings (room_id, during) VALUES (1, '[2026-03-02 09:30, 2026-03-02 11:00)');
-- ERROR: conflicting key value violates exclusion constraint "room_bookings_no_overlap"Read the EXCLUDE as: reject a new row if any existing row has the same room_id and an overlapping (&&) time range. The [...) range includes its start and excludes its end, so a 10:00 to 11:00 booking right after does not conflict.
Postgres 18 adds temporal keys, which express the same rule as a key: PRIMARY KEY (room_id, during WITHOUT OVERLAPS), backed by a GiST index (it also needs btree_gist for the plain columns). Postgres 18 can also declare temporal foreign keys with PERIOD. Neither exists in MySQL or SQLite; there you serialise bookings per room with a lock instead.
Generated columns
A generated column is computed from other columns in the same row, so it can never disagree with them. Useful for a line total, a normalised email to put a unique index on, or a field pulled out of JSON.
Press Run (⌘ Enter) to see what happens.A stored column is computed on write and kept on disk. A virtual one is computed when read. SQLite supports both and can index either. In Postgres, the expression must be immutable (no now(), no other tables), and the default changed in Postgres 18: a generated column with neither keyword is now virtual, and Postgres 18 cannot index virtual generated columns. If you want an index on it, write STORED explicitly, or index the expression itself.
Turning violations into API errors
When a constraint fires, your code gets an error with a standard five-character SQLSTATE code. Match on the code and the constraint name, never on the message text, which changes between versions and languages.
| SQLSTATE | Meaning | Usual API response |
|---|---|---|
23505 | unique violation | 409 Conflict ("email already registered") |
23503 | foreign key violation | 422 or 404 (the referenced thing does not exist) |
23502 | not-null violation | 422 (usually a bug: validate input first) |
23514 | check violation | 422 |
23P01 | exclusion violation | 409 ("that slot is taken") |
With psycopg 3, each code has its own exception class, and diag tells you which constraint fired:
from psycopg import errors
def create_customer(conn, name: str, email: str) -> tuple[int, dict]:
try:
with conn.transaction():
row = conn.execute(
"INSERT INTO customers (name, email) VALUES (%s, %s) RETURNING id",
(name, email),
).fetchone()
return 201, {"id": row[0]}
except errors.UniqueViolation as exc:
if exc.diag.constraint_name == "customers_email_key":
return 409, {"error": "email_taken"}
raiseSQLAlchemy wraps the same error in sqlalchemy.exc.IntegrityError, with the driver's exception on .orig. Errors and Middleware shows where to turn it into a response in a FastAPI app. SQLite has no SQLSTATE, so the runnable version has to read the message, which is exactly the fragility to avoid in Postgres:
Press Run (⌘ Enter) to see what happens.Adding constraints to a table that already has data
Adding a constraint means checking every existing row, and on a large Postgres table a plain ALTER TABLE ... ADD CONSTRAINT holds a lock that blocks writes while it scans. The production-safe versions split the work:
-- Foreign key or CHECK: add without checking old rows, then validate.
ALTER TABLE orders
ADD CONSTRAINT orders_customer_id_fkey
FOREIGN KEY (customer_id) REFERENCES customers (id) NOT VALID; -- quick; new writes are checked
ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_id_fkey; -- scans, but lets writes continue
-- UNIQUE: build the index without blocking writes, then attach it.
CREATE UNIQUE INDEX CONCURRENTLY customers_email_key ON customers (email);
ALTER TABLE customers
ADD CONSTRAINT customers_email_key UNIQUE USING INDEX customers_email_key;Before either, find and fix the rows that would fail, or validation stops halfway. Zero-Downtime Migrations covers the full playbook, including NOT NULL on a big table and lock timeouts.
Check your understanding
SELECT for the email, then INSERT if it is free, inside one transaction at Postgres's default isolation level. Duplicates still appear. Why?Customer 8 has no orders or events. What does this print?
from shopdb import connect
db = connect()
db.executescript("""
CREATE TABLE notes (
id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers(id) ON DELETE SET NULL
);
INSERT INTO notes (customer_id) VALUES (8), (8), (7);
""")
db.execute("DELETE FROM customers WHERE id = 8")
print(db.execute("SELECT COUNT(*), COUNT(customer_id) FROM notes").fetchone())Match each rule to the constraint that enforces it.
Put the steps for adding a foreign key to a busy 200-million-row Postgres table in order.
- Tap the steps below in the right order.
total_cents bigint GENERATED ALWAYS AS (quantity * unit_price_cents) and then try to index it. What happens?- constraint
- A rule the database enforces on every write, such as NOT NULL, UNIQUE, CHECK, a foreign key or an exclusion constraint.
- referential action
- What a foreign key does when its parent row is deleted or updated: NO ACTION, RESTRICT, CASCADE, SET NULL or SET DEFAULT.
- deferrable constraint
- A constraint whose check can wait until the end of the statement or until COMMIT, so a transaction can pass through invalid states.
- exclusion constraint
- A Postgres constraint that rejects a row if it conflicts with an existing row under given operators, such as the same room and overlapping time.
- generated column
- A column computed from others in the same row, either stored on write or computed on read (virtual).
- SQLSTATE
- A standard five-character error code. 23505 is a unique violation and 23503 a foreign key violation.
- NOT VALID
- A Postgres option that adds a foreign key or CHECK for new writes only, so old rows can be validated later without blocking writes.