Browse topics

CREATE TABLE and constraints

Version
19
Review
Draft

Summary#

CREATE TABLE defines columns and the rules their rows must satisfy. Primary keys, unique, foreign key, check and not-null constraints are enforced on writes by default.

Syntax#

sql
CREATE TABLE child (
    id        integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    parent_id integer NOT NULL REFERENCES parent ON DELETE CASCADE,
    code      text NOT NULL UNIQUE,
    quantity  integer NOT NULL DEFAULT 1,
    doubled   integer GENERATED ALWAYS AS (quantity * 2) STORED,
    CONSTRAINT positive_quantity CHECK (quantity > 0)
);

Example#

The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.

sql
BEGIN;

CREATE TEMPORARY TABLE invoices (
    invoice_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    reference  text NOT NULL UNIQUE
);

CREATE TEMPORARY TABLE invoice_lines (
    invoice_id integer NOT NULL REFERENCES invoices ON DELETE CASCADE,
    line_no    integer NOT NULL,
    quantity   integer NOT NULL DEFAULT 1,
    unit_price numeric(8,2) NOT NULL,
    total      numeric(10,2) GENERATED ALWAYS AS (quantity * unit_price) STORED,
    PRIMARY KEY (invoice_id, line_no),
    CONSTRAINT positive_quantity CHECK (quantity > 0)
);

INSERT INTO invoices (reference) VALUES ('INV-1');
INSERT INTO invoice_lines (invoice_id, line_no, quantity, unit_price)
VALUES (1, 1, 3, 2.50), (1, 2, DEFAULT, 10.00);

SELECT line_no, quantity, unit_price, total
FROM invoice_lines
ORDER BY line_no;

-- Catch the error to show which constraint rejected the row.
CREATE TEMPORARY TABLE rejected (constraint_name text);

DO $$
DECLARE
    violated text;
BEGIN
    INSERT INTO invoice_lines (invoice_id, line_no, quantity, unit_price)
    VALUES (1, 3, 0, 1.00);
EXCEPTION WHEN check_violation THEN
    GET STACKED DIAGNOSTICS violated = CONSTRAINT_NAME;
    INSERT INTO rejected VALUES (violated);
END
$$;

SELECT constraint_name FROM rejected;

DELETE FROM invoices WHERE reference = 'INV-1';
SELECT count(*) AS lines_left FROM invoice_lines;

ROLLBACK;

Expected output#

Text
line_no|quantity|unit_price|total
1|3|2.50|7.50
2|1|10.00|10.00
(2 rows)
constraint_name
positive_quantity
(1 row)
lines_left
0
(1 row)

Common mistakes#

A CHECK constraint passes when its expression is null, and UNIQUE treats nulls as distinct by default. Add NOT NULL when a value is required. Index the referencing columns of a foreign key when deletes or key updates on the parent need to find child rows quickly. Declaring the foreign key leaves that index up to you.

Version applicability#

Identity columns require PostgreSQL 10 and stored generated columns require 12. PostgreSQL 18 added virtual generated columns and made VIRTUAL the default, so the example states STORED explicitly.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0