Skip to content

17 / 32 · 5 min

Rules the database enforces itself

Application code can check that an email is unique and that an order belongs to a real customer. It will eventually fail to, because there will be a second application, a migration script, and someone at a console.

A rule enforced by the database cannot be bypassed by any of them.

Constraints

sql
CREATE TABLE orders (
    id          SERIAL PRIMARY KEY,
    customer_id INT NOT NULL REFERENCES customers(id),
    amount      NUMERIC(10,2) NOT NULL CHECK (amount > 0),
    email       TEXT UNIQUE,
    status      TEXT NOT NULL DEFAULT 'pending'
);
ConstraintGuarantees
PRIMARY KEYunique and not null, the row's identity
FOREIGN KEYthe referenced row exists
UNIQUEno duplicates in this column
NOT NULLa value is always present
CHECKan arbitrary condition holds
DEFAULTwhat to use when nothing is given

The foreign key is the one people disable for convenience and regret. Without it, deleting a customer leaves orders pointing at nothing, and the code that reads those orders crashes somewhere unrelated, months later.

ON DELETE says what should happen instead: CASCADE removes the children, RESTRICT refuses the delete, SET NULL orphans them deliberately. Choosing is a design decision, and the default of refusing is usually right.

Views

A view is a stored query that behaves like a table.

sql
CREATE VIEW active_customers AS
SELECT c.id, c.name, SUM(o.amount) AS lifetime_value
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.order_date >= CURRENT_DATE - INTERVAL '1 year'
GROUP BY c.id, c.name;

SELECT * FROM active_customers WHERE lifetime_value > 50000;

It stores no data. Every query against it runs the underlying query.

What it buys: one definition of "active customer" that every report shares, so two dashboards cannot quietly disagree. And a way to expose some columns of a table without exposing all of them.

A materialized view does store the result, so reads are fast and the data is as old as the last refresh. That is a cache with all the usual trade, and the same question applies: how stale is acceptable.