Constraints and keys

Topic 2 of 4 in Designing databases11 min readBeginnerFree course

Overview

Applications have bugs. Imports contain mistakes. People run quick fixes by hand. If the only thing keeping your data valid is the application code, sooner or later bad data gets in — a negative price, an order for a customer who doesn’t exist, two accounts with the same email. Constraints are rules you give the database itself, and it enforces them on every single write. They’re your last, and most reliable, line of defence.

Constraints: rules the database enforces. CREATE TABLE products ( id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, sku text NOT NULL UNIQUE, name text NOT NULL, price numeric(10,2) NOT NULL CHECK (price >= 0), category_id integer REFERENCES categories (id), stock integer NOT NULL DEFAULT 0 ). PRIMARY KEY: unique and not null, identifies each row. NOT NULL: a value is required. UNIQUE: no two rows may share the value. CHECK: any true/false rule on the row. FOREIGN KEY: must match a row in another table. DEFAULT: used when no value is given. Inserting a product with price -5 fails with: ERROR: new row for relation “products” violates check constraint “products_price_check”. Constraints are your last line of defence: every app, script and person that writes to the table must obey them. A violation rejects the whole statement — no half-written data.

NOT NULL

NOT NULL means the column must always have a value. Make it the default habit: most columns should be required, and every nullable column is a question every query has to answer (“what if it’s missing?”).

SQL
CREATE TABLE suppliers (
    id      integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name    text NOT NULL,
    email   text,
    country text NOT NULL DEFAULT 'Unknown'
);

INSERT INTO suppliers (email) VALUES ('hello@example.com');
Text
CREATE TABLE
ERROR:  null value in column "name" of relation "suppliers" violates not-null constraint
DETAIL:  Failing row contains (1, null, hello@example.com, Unknown).

UNIQUE

UNIQUE forbids two rows from having the same value. The shop’s customers.email is unique, so nobody can register twice with one address:

SQL
INSERT INTO customers (first_name, last_name, email, city, country, signup_date)
VALUES ('Asha', 'Rao', 'asha.rao@example.com', 'Pune', 'India', '2026-12-04');
Text
ERROR:  duplicate key value violates unique constraint "customers_email_key"
DETAIL:  Key (email)=(asha.rao@example.com) already exists.

Two details worth knowing:

  • NULLs don’t clash. A UNIQUE column can hold many NULLs, because NULL isn’t equal to NULL. (Since PostgreSQL 15, UNIQUE NULLS NOT DISTINCT treats them as equal if you need that.)
  • Case matters. 'Asha.Rao@example.com' is a different value from 'asha.rao@example.com'. To make emails unique regardless of case, create a unique index on lower(email) — see Indexes.

PRIMARY KEY

A primary key identifies each row: it’s UNIQUE and NOT NULL combined, and a table can have only one. Usually it’s a surrogate id column, but it can span several columns — a composite key. In Bean & Leaf, an order can contain each product only once, so order_items uses the pair as its key:

SQL
SELECT conname, contype, pg_get_constraintdef(oid) AS definition
FROM pg_constraint
WHERE conrelid = 'order_items'::regclass
  AND contype IN ('p', 'f', 'c', 'u')
ORDER BY conname;
Text
           conname           | contype |                           definition                           
-----------------------------+---------+----------------------------------------------------------------
 order_items_order_id_fkey   | f       | FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE
 order_items_pkey            | p       | PRIMARY KEY (order_id, product_id)
 order_items_product_id_fkey | f       | FOREIGN KEY (product_id) REFERENCES products(id)
 order_items_quantity_check  | c       | CHECK ((quantity > 0))
(4 rows)

(pg_constraint is the system catalog of constraints; contype is p for primary key, f for foreign key, c for check and u for unique. Since PostgreSQL 18, NOT NULL constraints are listed there too, as n, which the query leaves out.) Adding the same product to an order twice is refused — you’d increase the quantity instead:

SQL
INSERT INTO order_items (order_id, product_id, quantity, unit_price)
VALUES (1, 1, 1, 14.50);
Text
ERROR:  duplicate key value violates unique constraint "order_items_pkey"
DETAIL:  Key (order_id, product_id)=(1, 1) already exists.

Surrogate or natural keys? A natural key is a real-world value, like an email or a SKU. A surrogate key is a meaningless id. Real-world values change (people change emails; suppliers renumber products), and when a primary key changes, every foreign key pointing at it has to change too. The common practice: a surrogate id as the primary key, plus UNIQUE constraints on the natural keys.

CHECK

A CHECK constraint enforces any condition that can be tested on a single row. Column-level checks test one column; table-level checks, written after the columns, can compare several:

SQL
CREATE TABLE promotions (
    id         integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    code       text NOT NULL UNIQUE CHECK (code = upper(code)),
    percent    integer NOT NULL CHECK (percent BETWEEN 1 AND 90),
    starts_on  date NOT NULL,
    ends_on    date NOT NULL,
    CONSTRAINT ends_after_start CHECK (ends_on > starts_on)
);

INSERT INTO promotions (code, percent, starts_on, ends_on)
VALUES ('WINTER10', 10, '2026-12-01', '2026-12-31');

INSERT INTO promotions (code, percent, starts_on, ends_on)
VALUES ('OOPS', 15, '2026-12-31', '2026-12-01');
Text
CREATE TABLE
INSERT 0 1
ERROR:  new row for relation "promotions" violates check constraint "ends_after_start"
DETAIL:  Failing row contains (2, OOPS, 15, 2026-12-31, 2026-12-01).

Because the second check was named with CONSTRAINT ends_after_start, the error says exactly which rule failed. Unnamed constraints get generated names like promotions_percent_check — fine, but a good name makes errors self-explanatory, so name the important ones.

A CHECK passes when the condition is true or NULL, so CHECK (percent > 0) alone doesn’t stop a NULL percent — combine it with NOT NULL. And a check can only look at its own row; rules involving other rows (“no overlapping promotions”) need a unique constraint, an exclusion constraint or a trigger.

FOREIGN KEY

A foreign key (REFERENCES) requires every value in a column to match a primary key (or unique) value in another table — this is what keeps relationships valid. You’ve seen it refuse an order for a customer who doesn’t exist, and refuse to delete a customer who has orders.

What happens to child rows when a parent row is deleted is set by an ON DELETE action:

Action When the parent is deleted… Good for
NO ACTION / RESTRICT (default) refuse, if children exist important records: customers, orders
CASCADE delete the children too parts that can’t exist alone: order lines, review photos
SET NULL keep the children, set the foreign key to NULL optional links: a product’s category
SET DEFAULT keep the children, set the key to its default rare

There’s a matching ON UPDATE, rarely needed when primary keys never change. Here’s SET NULL in action on a small example:

SQL
CREATE TABLE brands (
    id   integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name text NOT NULL UNIQUE
);
CREATE TABLE brand_products (
    id       integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name     text NOT NULL,
    brand_id integer REFERENCES brands (id) ON DELETE SET NULL
);
INSERT INTO brands (name) VALUES ('Hario'), ('Bodum');
INSERT INTO brand_products (name, brand_id) VALUES ('V60 Dripper', 1), ('French Press', 2);

DELETE FROM brands WHERE name = 'Bodum';
SELECT * FROM brand_products ORDER BY id;
Text
CREATE TABLE
CREATE TABLE
INSERT 0 2
INSERT 0 2
DELETE 1
 id |     name     | brand_id 
----+--------------+----------
  1 | V60 Dripper  |        1
  2 | French Press |         
(2 rows)

The French Press survived, with no brand. A foreign key column can be NULL unless you also declare it NOT NULL — that’s how “optional” relationships are modelled.

Constraints are checked on every write

Constraints apply to INSERT, UPDATE, COPY — everything. An update that would break a rule is refused just like an insert:

SQL
UPDATE products SET stock = stock - 50 WHERE id = 5;
Text
UPDATE 1

Assam has 80 in stock, so 30 would remain — fine. But try once more:

SQL
UPDATE products SET stock = stock - 50 WHERE id = 5;
Text
ERROR:  new row for relation "products" violates check constraint "products_stock_check"
DETAIL:  Failing row contains (5, Assam Breakfast, 2, 9.50, -20).

The database itself prevents overselling, whatever bug or race condition might exist in the application.

Tip: design constraints as carefully as columns. For every column ask: can it be missing? must it be unique? what values are impossible? does it point at another table? Each answer is a constraint — and each constraint is a class of bug that can never reach your data.

Exercise

One review per customer per product

Create a reviews table with: id (integer identity primary key); product_id (required, a foreign key to products(id) that deletes the review if the product is deleted); customer_id (required, a foreign key to customers(id)); rating (required integer, a CHECK that it's between 1 and 5); body (optional text); and a constraint named one_review_each that makes the pair (product_id, customer_id) unique. Then test it: insert a valid review (product 1, customer 1, rating 5, body 'Superb'); try a second review of product 1 by customer 1 (it must fail); try a review with rating 6 (it must fail); and finally count the rows in reviews — there should be 1.

SQL
CREATE TABLE reviews (
  id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY
  -- columns and constraints
);

Summary

  • Constraints are rules the database enforces on every write, whatever program or person makes it.
  • NOT NULL requires a value; UNIQUE forbids duplicates; PRIMARY KEY is unique and not null and identifies each row.
  • CHECK enforces any true/false condition on a row; FOREIGN KEY (REFERENCES) requires a matching row in another table.
  • Constraints can span several columns, such as a composite primary key or UNIQUE (product_id, customer_id).
  • ON DELETE CASCADE / SET NULL / RESTRICT decide what happens to child rows when a parent is deleted; name constraints so error messages are clear.