Skip to content

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.

20 min read0/5 questions

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.

Two sign-ups for the same email
Server ADatabaseServer BSELECT ... email = sam@no rowsSELECT ... email = sam@no rowsINSERT sam@INSERT sam@

Server A checks whether the email is taken.

1/6

Here is the same interleaving with two real connections to one database file. The first table has no rule; the second has UNIQUE.

Pythonsignup_race.py
import sqlite3from shopdb import connect path = "/tmp/shop.db"connect(path).close() # creates a fresh file database with the dataset # Two app servers, two connections, one table with no UNIQUE rule.a = sqlite3.connect(path, isolation_level=None)b = sqlite3.connect(path, isolation_level=None)a.execute("CREATE TABLE signups (email TEXT NOT NULL)") def taken(conn, email): return conn.execute("SELECT 1 FROM signups WHERE email = ?", (email,)).fetchone() is not None email = "sam@example.com"print("A checks:", "taken" if taken(a, email) else "free")print("B checks:", "taken" if taken(b, email) else "free")a.execute("INSERT INTO signups VALUES (?)", (email,))b.execute("INSERT INTO signups VALUES (?)", (email,))print("rows for sam:", a.execute("SELECT COUNT(*) FROM signups WHERE email = ?", (email,)).fetchone()[0]) # Same interleaving, but the database owns the rule.a.execute("CREATE TABLE signups2 (email TEXT NOT NULL UNIQUE)")print("A checks:", "taken" if a.execute("SELECT 1 FROM signups2 WHERE email = ?", (email,)).fetchone() else "free")print("B checks:", "taken" if b.execute("SELECT 1 FROM signups2 WHERE email = ?", (email,)).fetchone() else "free")a.execute("INSERT INTO signups2 VALUES (?)", (email,))try: b.execute("INSERT INTO signups2 VALUES (?)", (email,))except sqlite3.IntegrityError as err: print("B's insert refused:", err)
Output
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 NULL is the cheapest and most valuable. Make every column NOT NULL unless "unknown" is a real state you will handle. Adding it later to a big table is much harder than starting with it.
  • DEFAULT is not a constraint, but it pairs with NOT 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 as ends_on > starts_on. It cannot look at other rows or other tables; that needs a constraint type built for it, or a trigger.
  • UNIQUE can span several columns. UNIQUE (store_id, code) lets two stores both have a SPRING coupon but stops one store having two.
  • PRIMARY KEY is UNIQUE plus NOT 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.

Pythoncheck_and_unique.py
import sqlite3from shopdb import connect, showdb = connect() db.executescript("""CREATE TABLE coupons ( code TEXT NOT NULL, store_id INTEGER NOT NULL, percent_off INTEGER NOT NULL DEFAULT 10, starts_on TEXT NOT NULL, ends_on TEXT, CONSTRAINT coupons_percent_range CHECK (percent_off BETWEEN 1 AND 90), CONSTRAINT coupons_dates_ordered CHECK (ends_on IS NULL OR ends_on > starts_on), CONSTRAINT coupons_code_per_store UNIQUE (store_id, code));""") attempts = [ ("valid", "INSERT INTO coupons (code, store_id, starts_on) VALUES ('SPRING', 1, '2025-03-01')"), ("same code, other store", "INSERT INTO coupons (code, store_id, starts_on) VALUES ('SPRING', 2, '2025-03-01')"), ("same code, same store", "INSERT INTO coupons (code, store_id, starts_on) VALUES ('SPRING', 1, '2025-04-01')"), ("150 percent off", "INSERT INTO coupons VALUES ('BIG', 1, 150, '2025-03-01', NULL)"), ("ends before it starts", "INSERT INTO coupons VALUES ('OOPS', 1, 20, '2025-03-01', '2025-02-01')"), ("no end date (NULL passes)", "INSERT INTO coupons VALUES ('FOREVER', 1, 5, '2025-03-01', NULL)"),]for label, sql in attempts: try: db.execute(sql) print(f"{label}: ok") except sqlite3.IntegrityError as err: print(f"{label}: {err}") show(db, "SELECT * FROM coupons")
Output
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.

Pythonunique_nulls.py
import sqlite3from shopdb import connect, showdb = connect() db.executescript("""CREATE TABLE accounts (id INTEGER PRIMARY KEY, email TEXT UNIQUE);INSERT INTO accounts (email) VALUES (NULL), (NULL), ('kim@example.com');""")show(db, "SELECT * FROM accounts")try: db.execute("INSERT INTO accounts (email) VALUES ('kim@example.com')")except sqlite3.IntegrityError as err: print(err)
Output
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:

ActionDeleting the parent...Typical use
NO ACTION (default)fails if children exist; checked at the end of the statementmost relationships
RESTRICTfails if children exist; checked immediately, cannot be deferredthe same, stated loudly
CASCADEdeletes the children toorows that cannot exist alone: order lines, a post's comments
SET NULLsets the child's column to NULLoptional links: a comment whose author left
SET DEFAULTsets the child's column to its defaultrare
Pythonon_delete.py
import sqlite3from shopdb import connect, showdb = connect() db.executescript("""CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT NOT NULL);CREATE TABLE posts ( id INTEGER PRIMARY KEY, author_id INTEGER NOT NULL REFERENCES authors(id) ON DELETE CASCADE, title TEXT NOT NULL);CREATE TABLE comments ( id INTEGER PRIMARY KEY, post_id INTEGER NOT NULL REFERENCES posts(id) ON DELETE CASCADE, author_id INTEGER REFERENCES authors(id) ON DELETE SET NULL, body TEXT NOT NULL);CREATE TABLE invoices ( id INTEGER PRIMARY KEY, author_id INTEGER NOT NULL REFERENCES authors(id) ON DELETE RESTRICT, total INTEGER NOT NULL);INSERT INTO authors VALUES (1, 'Ada'), (2, 'Grace');INSERT INTO posts VALUES (10, 1, 'Notes on the Engine'), (11, 2, 'Compilers');INSERT INTO comments VALUES (100, 10, 2, 'Great post'), (101, 11, 1, 'Agreed'), (102, 11, 2, 'Thanks');INSERT INTO invoices VALUES (500, 2, 9900);""") db.execute("DELETE FROM authors WHERE id = 1")show(db, "SELECT * FROM posts")show(db, "SELECT * FROM comments") try: db.execute("DELETE FROM authors WHERE id = 2")except sqlite3.IntegrityError as err: print("deleting Grace:", err)
Output
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.

Pythonforeign_key_audit.py
import sqlite3from shopdb import SEED, show # A connection that forgot the pragma: orphans slip in.db = sqlite3.connect(":memory:")db.executescript(SEED)db.execute("INSERT INTO orders (customer_id, status, created_at) VALUES (42, 'paid', '2025-08-01')")db.execute("INSERT INTO order_items VALUES (1, 999, 1, 100)") # Python's sqlite3 opened a transaction for those INSERTs,# and the pragma is silently ignored inside a transaction.db.execute("PRAGMA foreign_keys = ON")print("in a transaction:", db.in_transaction, "| enforced:", db.execute("PRAGMA foreign_keys").fetchone()[0]) db.commit()db.execute("PRAGMA foreign_keys = ON")print("after commit: ", db.in_transaction, "| enforced:", db.execute("PRAGMA foreign_keys").fetchone()[0]) # Enforcement only applies to new writes. Audit the old rows explicitly.show(db, 'SELECT "table", rowid, parent FROM pragma_foreign_key_check() ORDER BY "table"')
Output
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:

Pythondeferred_fk.py
import sqlite3from shopdb import connect, showdb = connect()db.isolation_level = None # we write BEGIN and COMMIT ourselves # Every team has a lead, and every lead belongs to a team: a cycle.db.executescript("""CREATE TABLE teams ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, lead_id INTEGER NOT NULL REFERENCES people(id) DEFERRABLE INITIALLY DEFERRED);CREATE TABLE people ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, team_id INTEGER NOT NULL REFERENCES teams(id) DEFERRABLE INITIALLY DEFERRED);""") db.execute("BEGIN")db.execute("INSERT INTO teams VALUES (1, 'Payments', 7)") # person 7 does not exist yetdb.execute("INSERT INTO people VALUES (7, 'Rita', 1)")db.execute("COMMIT") # checked here, and it holdsshow(db, "SELECT t.name AS team, p.name AS lead FROM teams t JOIN people p ON p.id = t.lead_id") db.execute("BEGIN")db.execute("INSERT INTO teams VALUES (2, 'Search', 99)") # nobody ever becomes person 99try: db.execute("COMMIT")except sqlite3.IntegrityError as err: print("commit refused:", err) db.execute("ROLLBACK")show(db, "SELECT id, name FROM teams")
Output
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:

Pythonunique_shift.py
import sqlite3from shopdb import connect, showdb = connect() db.executescript("""CREATE TABLE playlist ( song TEXT NOT NULL, position INTEGER NOT NULL UNIQUE);INSERT INTO playlist VALUES ('Intro', 1), ('Verse', 2), ('Outro', 3);""")# Insert a new song at the top: shift everyone down by one.try: db.execute("UPDATE playlist SET position = position + 1") print("shift worked")except sqlite3.IntegrityError as err: print("shift failed:", err)show(db, "SELECT * FROM playlist ORDER BY position") # A portable workaround: move the rows out of the way, then into place.db.execute("UPDATE playlist SET position = -position")db.execute("UPDATE playlist SET position = -position + 1")db.execute("INSERT INTO playlist VALUES ('Cold open', 1)")show(db, "SELECT * FROM playlist ORDER BY position")
Output
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:

deferrable.sql
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:

bookings.sql
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.

Pythongenerated_columns.py
import sqlite3from shopdb import connect, showdb = connect() db.executescript("""CREATE TABLE line_totals ( order_id INTEGER NOT NULL, quantity INTEGER NOT NULL CHECK (quantity > 0), unit_price_cents INTEGER NOT NULL CHECK (unit_price_cents >= 0), total_cents INTEGER GENERATED ALWAYS AS (quantity * unit_price_cents) STORED, email TEXT, email_key TEXT GENERATED ALWAYS AS (lower(trim(email))) VIRTUAL);CREATE INDEX line_totals_total ON line_totals (total_cents);CREATE UNIQUE INDEX line_totals_email_key ON line_totals (email_key);INSERT INTO line_totals (order_id, quantity, unit_price_cents)SELECT order_id, quantity, unit_price_cents FROM order_items WHERE order_id <= 2;""")show(db, "SELECT order_id, quantity, unit_price_cents, total_cents FROM line_totals") for sql in [ "INSERT INTO line_totals (order_id, quantity, unit_price_cents, total_cents) VALUES (3, 1, 100, 5)", "INSERT INTO line_totals (order_id, quantity, unit_price_cents, email) VALUES (3, 1, 100, 'Ana@Example.com')", "INSERT INTO line_totals (order_id, quantity, unit_price_cents, email) VALUES (4, 1, 100, ' ana@example.COM ')",]: try: db.execute(sql) print("ok") except sqlite3.Error as err: print(type(err).__name__, "->", err)
Output
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.

SQLSTATEMeaningUsual API response
23505unique violation409 Conflict ("email already registered")
23503foreign key violation422 or 404 (the referenced thing does not exist)
23502not-null violation422 (usually a bug: validate input first)
23514check violation422
23P01exclusion violation409 ("that slot is taken")

With psycopg 3, each code has its own exception class, and diag tells you which constraint fired:

app/customers.py
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"}
        raise

SQLAlchemy 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:

Pythonmap_errors.py
import sqlite3from shopdb import connect db = connect()db.isolation_level = None def create_customer(name, email): """Return (status, body) the way an API handler would.""" try: cur = db.execute( "INSERT INTO customers (name, email, created_at) VALUES (?, ?, date('now')) RETURNING id", (name, email), ) return 201, {"id": cur.fetchone()[0]} except sqlite3.IntegrityError as err: msg = str(err) if msg.startswith("UNIQUE constraint failed: customers.email"): return 409, {"error": "email_taken"} if msg.startswith("NOT NULL constraint failed"): return 422, {"error": "missing_field", "detail": msg.split(": ")[1]} raise print(create_customer("Hedy Lamarr", "hedy@example.com"))print(create_customer("Ada Again", "ada@example.com"))print(create_customer(None, "noname@example.com")) # Often better than catching: say what a conflict should do.row = db.execute("""INSERT INTO customers (name, email, created_at) VALUES ('Ada L.', 'ada@example.com', date('now'))ON CONFLICT (email) DO NOTHINGRETURNING id""").fetchone()print("upsert returned:", row)
Output
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:

add_constraints_safely.sql
-- 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

Quick check
Your sign-up handler runs SELECT for the email, then INSERT if it is free, inside one transaction at Postgres's default isolation level. Duplicates still appear. Why?
Need a nudge? A hint rules out a wrong answer.
Predict the outputPython

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())
Need a nudge? Hints walk you through it.
Match the pairs0/6 matched

Match each rule to the constraint that enforces it.

Choose an item, then its match on the other side.
Put it in order5 steps

Put the steps for adding a foreign key to a busy 200-million-row Postgres table in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
On Postgres 18 you add total_cents bigint GENERATED ALWAYS AS (quantity * unit_price_cents) and then try to index it. What happens?
Need a nudge? A hint rules out a wrong answer.
Key terms
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.