TExcelTAD
Home › PostgreSQL › PostgreSQL Constraints & Keys

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:

pgsql · try it yourself
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):

pgsql · try it yourself
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:

pgsql · try it yourself
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:

pgsql · try it yourself
CREATE TABLE coupons (
    code      text PRIMARY KEY CHECK (code ~ '^[A-Z0-9]{4,12}
  

),
    percent   integer CHECK (percent BETWEEN 1 AND 90)
);
INSERT INTO coupons VALUES ('SPRING25', 25);
INSERT INTO coupons VALUES ('spring', 10);
INSERT INTO coupons VALUES ('NOLIMIT', NULL);
SELECT * FROM coupons;
CREATE TABLE
INSERT 0 1
ERROR:  new row for relation "coupons" violates check constraint "coupons_code_check"
DETAIL:  Failing row contains (spring, 10).
INSERT 0 1
   code   | percent
----------+---------
 SPRING25 |      25
 NOLIMIT  |
(2 rows)

Adding and removing constraints later

ALTER TABLE adds or drops constraints on an existing table. Adding one checks the existing rows first:

pgsql · try it yourself
ALTER TABLE customers ADD CONSTRAINT email_has_at CHECK (email LIKE '%@%');
UPDATE customers SET email = 'not-an-email' WHERE id = 1;

ALTER TABLE books ADD CONSTRAINT stock_limit CHECK (stock <= 25);

ALTER TABLE customers DROP CONSTRAINT email_has_at;
UPDATE customers SET email = 'not-an-email' WHERE id = 1;
ALTER TABLE
ERROR:  new row for relation "customers" violates check constraint "email_has_at"
DETAIL:  Failing row contains (1, Anna, Kowalski, not-an-email, Warsaw, Poland, 2023-01-15).
ERROR:  check constraint "stock_limit" of relation "books" is violated by some row
ALTER TABLE
UPDATE 1

The email rule is added (the three NULL emails pass, as explained above) and immediately blocks the bad update. Adding the stock limit fails because Ten Tiny Dragons already has 30 copies. After dropping email_has_at, nothing stops a broken email again.

Tip: Name your constraints (CONSTRAINT due_after_loan CHECK …). The name appears in every error message, which helps application code show a friendly message.

Test yourself

What is a PRIMARY KEY equivalent to?

  1. UNIQUE only
  2. NOT NULL only
  3. UNIQUE plus NOT NULL
  4. A foreign key

A CHECK (price > 0) constraint receives a NULL price. What happens?

  1. The insert fails
  2. The row is accepted, because the check is not false
  3. The price becomes 0
  4. PostgreSQL asks for a value

With REFERENCES customers (id) ON DELETE CASCADE, what happens when a customer is deleted?

  1. The delete is blocked
  2. Referencing rows are deleted too
  3. Referencing rows get NULL
  4. Nothing