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
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'
);| Constraint | Guarantees |
|---|---|
| PRIMARY KEY | unique and not null, the row's identity |
| FOREIGN KEY | the referenced row exists |
| UNIQUE | no duplicates in this column |
| NOT NULL | a value is always present |
| CHECK | an arbitrary condition holds |
| DEFAULT | what 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.
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.