A constraint is a guarantee; application validation is a hope. This is the organising idea of the module. Any rule enforced only in a service is a rule that is false the first time somebody connects with psql, runs a migration, or writes a second service. Put it in the schema.
NOT NULL is the one people under-use. A nullable column forces every reader to handle a case that may not exist, and NULL propagates through comparisons in ways that surprise people - NULL = NULL is NULL, not true. CHECK encodes a predicate about one row. UNIQUE and PRIMARY KEY encode identity. FOREIGN KEY encodes a relationship, and its ON DELETE clause is a design decision rather than a detail: CASCADE when the child is meaningless without the parent, RESTRICT when deleting the parent should be refused, SET NULL when the relationship is optional.
Identity columns (GENERATED ALWAYS AS IDENTITY) are the standard-conforming replacement for serial. Prefer them: serial leaves the sequence's ownership and permissions subtly wrong, and GENERATED ALWAYS prevents an application from inserting its own value by accident.
Normalization is a tool, not a target. Third normal form removes update anomalies - the same fact stored twice can disagree with itself. That is worth having by default. Denormalization is the deliberate reintroduction of a duplicate for a read that cannot otherwise be served fast enough, and it is a trade you make once you have measured, having written down what now keeps the copy correct. "We denormalized for performance" without a benchmark is a schema that is wrong for no reason.
The question that should drive the design is not "what are the entities" but "what are the access patterns". The same domain produces different correct schemas depending on whether it is read by key, scanned by range, or aggregated by group.
The query features that matter. Joins you already know. The three worth real practice:
CTEs (WITH) name a subquery and make a long query readable top to bottom. Since PostgreSQL 12 they are not an optimisation fence by default, so you can use them freely; MATERIALIZED forces the old behaviour when you want it.
Window functions compute across a set of rows without collapsing them, which is the part that distinguishes them from GROUP BY. A running total, a rank within a group, each row beside the previous one - all are a window function and none need application code.
LATERAL lets a subquery in the FROM clause reference columns from preceding items, which is how you express "the three most recent orders for each customer" in one statement.
Laboratory exercise 2 - two competing models.
Design two schemas for the capstone's banking ledger, with genuinely different shapes - for example, a mutable balance column against an append-only entry table with the balance derived. Implement both. Write the representative queries for each: post a transfer, read a balance, list a statement for a period, and find accounts whose balance disagrees with the sum of their entries.
Validate the invariants on both. The ledger's rule is that every transfer's entries sum to zero and no account's derived balance disagrees with its recorded one.
Deliverable: both schemas, the queries, a test that attempts to violate each invariant and shows the database refusing, and a page arguing for one model against the stated access patterns. The argument is the assessed part. "It felt cleaner" is not an argument; "the append-only model makes the statement query a range scan on one index and makes the balance a derived aggregate we must cache, and we read statements 50 times for every transfer" is.
-- ------------------------------------------------------------------
-- Model B: append-only entries, balance derived. Double-entry means
-- every transfer writes two rows that sum to zero.
-- ------------------------------------------------------------------
CREATE TABLE ledger.transfer (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
created_at timestamptz NOT NULL DEFAULT now(),
reference text NOT NULL UNIQUE -- idempotency key
);
CREATE TABLE ledger.entry (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
transfer_id bigint NOT NULL REFERENCES ledger.transfer(id)
ON DELETE RESTRICT,
-- ^^^^^^^^ a posted transfer is a historical
-- fact. Deleting one should be refused, not
-- cascaded.
account_id bigint NOT NULL REFERENCES ledger.account(id),
amount_minor bigint NOT NULL CHECK (amount_minor <> 0),
created_at timestamptz NOT NULL DEFAULT now()
);
-- The index that serves the statement query. Column order matters:
-- account first, because that is what we filter on; then time, so the
-- range is contiguous within each account.
CREATE INDEX entry_by_account_time
ON ledger.entry (account_id, created_at DESC);
-- The double-entry invariant, enforced by the database rather than by
-- whoever remembers to call the validation function.
CREATE OR REPLACE FUNCTION ledger.transfer_balances()
RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE total bigint;
BEGIN
SELECT sum(amount_minor) INTO total
FROM ledger.entry WHERE transfer_id = NEW.transfer_id;
IF total <> 0 THEN
RAISE EXCEPTION 'transfer % does not balance: %', NEW.transfer_id, total;
END IF;
RETURN NULL;
END $$;
CREATE CONSTRAINT TRIGGER transfer_must_balance
AFTER INSERT ON ledger.entry
DEFERRABLE INITIALLY DEFERRED -- checked at COMMIT, so the two
FOR EACH ROW -- halves may be inserted in turn
EXECUTE FUNCTION ledger.transfer_balances();
-- ------------------------------------------------------------------
-- Posting a transfer. Both halves, one transaction, one reference.
-- ------------------------------------------------------------------
BEGIN;
WITH t AS (
INSERT INTO ledger.transfer (reference) VALUES ('tr-0001')
RETURNING id
)
INSERT INTO ledger.entry (transfer_id, account_id, amount_minor)
SELECT t.id, a.account_id, a.amount
FROM t, (VALUES (1, -5000), (2, 5000)) AS a(account_id, amount);
COMMIT;
-- ------------------------------------------------------------------
-- CTEs, window functions and LATERAL - the three worth practising.
-- ------------------------------------------------------------------
-- A statement with a running balance. The window function computes
-- across rows WITHOUT collapsing them, which GROUP BY cannot do.
WITH recent AS (
SELECT e.created_at, e.amount_minor, t.reference
FROM ledger.entry e
JOIN ledger.transfer t ON t.id = e.transfer_id
WHERE e.account_id = 1
AND e.created_at >= now() - interval '90 days'
)
SELECT
created_at,
reference,
amount_minor,
sum(amount_minor) OVER (ORDER BY created_at
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
AS running_balance,
lag(created_at) OVER (ORDER BY created_at) AS previous_entry
FROM recent
ORDER BY created_at;
-- Rank within a group, without a self-join:
SELECT account_id, amount_minor,
row_number() OVER (PARTITION BY account_id ORDER BY created_at DESC) AS n
FROM ledger.entry;
-- LATERAL: the three most recent entries for EACH account. The
-- subquery references a.id from the row to its left, which is the
-- thing a plain subquery cannot do.
SELECT a.id, a.holder, e.created_at, e.amount_minor
FROM ledger.account a
CROSS JOIN LATERAL (
SELECT created_at, amount_minor
FROM ledger.entry
WHERE account_id = a.id
ORDER BY created_at DESC
LIMIT 3
) AS e
WHERE a.tags @> ARRAY['vip'];
-- The reconciliation query: where does the recorded balance disagree
-- with the entries? On a correct system this returns nothing, and it
-- is worth running as a scheduled assertion.
SELECT a.id, a.balance_minor, coalesce(sum(e.amount_minor), 0) AS derived
FROM ledger.account a
LEFT JOIN ledger.entry e ON e.account_id = a.id
GROUP BY a.id, a.balance_minor
HAVING a.balance_minor <> coalesce(sum(e.amount_minor), 0);
Discussion
No questions on this topic yet. Sign in to ask the first one.