PostgreSQL Constraints & Keys
Constraints are rules that the database enforces on every insert and update. They are your last line of defence against bad data: no matter which program or person writes to the table, a constraint cannot be bypassed.
| Constraint | Rule |
|---|---|
NOT NULL |
a value is required |
UNIQUE |
no two rows may have the same value (NULLs are allowed, and by default don't clash) |
PRIMARY KEY |
UNIQUE + NOT NULL; identifies each row; one per table |
FOREIGN KEY / REFERENCES |
the value must exist in another table |
CHECK (condition) |
the condition must not be false |
EXCLUDE |
no two rows may "overlap" (advanced, e.g. room bookings) |
Column and table constraints
Constraints can be written next to a column, or as separate lines in the table definition. Table constraints can cover several columns, and you can name them so error messages are clearer:
CREATE TABLE loans (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
book_id integer NOT NULL REFERENCES books (id),
customer_id integer NOT NULL REFERENCES customers (id),
loaned_on date NOT NULL,
due_on date NOT NULL,
CONSTRAINT due_after_loan CHECK (due_on > loaned_on),
CONSTRAINT one_copy_per_customer UNIQUE (book_id, customer_id)
);
INSERT INTO loans (book_id, customer_id, loaned_on, due_on) VALUES (1, 1, '2025-01-10', '2025-01-24');
INSERT INTO loans (book_id, customer_id, loaned_on, due_on) VALUES (1, 1, '2025-02-01', '2025-02-15');
INSERT INTO loans (book_id, customer_id, loaned_on, due_on) VALUES (2, 1, '2025-02-01', '2025-01-15');CREATE TABLE
INSERT 0 1
ERROR: duplicate key value violates unique constraint "one_copy_per_customer"
DETAIL: Key (book_id, customer_id)=(1, 1) already exists.
ERROR: new row for relation "loans" violates check constraint "due_after_loan"
DETAIL: Failing row contains (3, 2, 1, 2025-02-01, 2025-01-15).
Primary keys
Every table should have a primary key. It is usually a single generated number (a surrogate key), but it can also be a combination of columns (a composite key), as in order_items (order_id, book_id):
INSERT INTO order_items (order_id, book_id, quantity, unit_price) VALUES (1, 1, 5, 14.99);
SELECT tc.constraint_name, tc.constraint_type, kcu.column_name
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu
ON kcu.constraint_name = tc.constraint_name
WHERE tc.table_name = 'order_items'
ORDER BY tc.constraint_type DESC, kcu.ordinal_position;ERROR: duplicate key value violates unique constraint "order_items_pkey"
DETAIL: Key (order_id, book_id)=(1, 1) already exists.
constraint_name | constraint_type | column_name
---------------------------+-----------------+-------------
order_items_pkey | PRIMARY KEY | order_id
order_items_pkey | PRIMARY KEY | book_id
order_items_order_id_fkey | FOREIGN KEY | order_id
order_items_book_id_fkey | FOREIGN KEY | book_id
(4 rows)
Foreign keys and referential actions
A foreign key says "this value must exist over there". The ON DELETE / ON UPDATE actions decide what happens when the referenced row changes:
CREATE TABLE wishlists (
customer_id integer REFERENCES customers (id) ON DELETE CASCADE,
book_id integer REFERENCES books (id) ON DELETE SET NULL,
note text
);
INSERT INTO wishlists VALUES (7, 2, 'birthday'), (7, 12, 'maybe'), (13, 16, 'winter');
DELETE FROM books WHERE id = 2; -- never sold, so allowed
DELETE FROM customers WHERE id = 13; -- never ordered, so allowed
SELECT * FROM wishlists ORDER BY note;CREATE TABLE
INSERT 0 3
DELETE 1
DELETE 1
customer_id | book_id | note
-------------+---------+----------
7 | | birthday
7 | 12 | maybe
(2 rows)
Deleting book 2 set the wishlist's book_id to NULL; deleting customer 13 removed that customer's wishlist row entirely.
CHECK constraints
A CHECK can use any expression on the row's own columns. A row passes when the expression is true or NULL, so combine it with NOT NULL when the value is required:
CREATE TABLE coupons (
code text PRIMARY KEY CHECK (code ~ '^[A-Z0-9]{4,12}