Part 13 / Stage 3
Reusable logic
Goal: Put logic in the database where it belongs — views and materialized views, recursive CTEs, SQL and PL/pgSQL functions, procedures, triggers — and know the honest cost of each. Time: ~2.5 hours
What you will learn
- Views: saved queries, and when they're updatable
- Materialized views: stored results,
REFRESH, and the CONCURRENTLY rule - Recursive CTEs: org charts and category trees
- SQL functions:
CREATE FUNCTION, parameters, volatility - PL/pgSQL: variables, IF, loops, RAISE
- Procedures:
CALL, and transaction control inside - Triggers: BEFORE/AFTER, row vs statement, a real audit log
- When not to put logic in the database
Everything runs on shopdb — and builds objects in it, so reseed when you want a clean slate.
Topics in this part
Practice
SQL workbench — write and run queries here
Press Run and PostgreSQL loads right in your browser (a one-time download of about 16 MB; after that it works offline). It comes seeded with shopdb, and statements share one session per page — like a psql window. Reset data rebuilds shopdb. Your queries never leave this page. Lessons were captured on PostgreSQL 17; the in-browser server is PostgreSQL 19 (via PGlite), so the rare output detail can differ.
These create objects in shopdb; every solution is re-runnable (it drops its own objects first). Reseed any time.
Exercise 1: The category revenue view
What to do: Wrap the delivered-revenue-per-category join (Part 5's four-table classic) in a view, then answer "categories over 300" with a one-liner against it.
Sample output:
category | revenue
----------+---------
Laptops | 2400.00
Phones | 1198.00
Books | 340.00
(3 rows)
💡 Hint: the view holds the join; your query holds only the question.
Show the solution to Exercise 1
-- Exercise 1: The category revenue view (re-runnable)
DROP VIEW IF EXISTS category_revenue;
CREATE VIEW category_revenue AS
SELECT cat.name AS category,
sum(oi.quantity * oi.unit_price) AS revenue
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
JOIN products p ON p.product_id = oi.product_id
JOIN categories cat ON cat.category_id = p.category_id
WHERE o.status = 'delivered'
GROUP BY cat.name;
SELECT * FROM category_revenue WHERE revenue > 300 ORDER BY revenue DESC;
Exercise 2: The spend matview
What to do: Materialize per-customer non-cancelled spend, then make REFRESH ... CONCURRENTLY work. (Try the refresh before creating the index once — read the hint Postgres gives you.)
Sample output:
customer_id | spend
-------------+---------
3 | 2108.00
1 | 1525.00
2 | 949.00
5 | 399.00
(4 rows)
💡 Hint: CREATE UNIQUE INDEX ... ON customer_spend_mv (customer_id); — the error's HINT says exactly this.
Show the solution to Exercise 2
-- Exercise 2: The spend matview, refreshable without blocking (re-runnable)
DROP MATERIALIZED VIEW IF EXISTS customer_spend_mv;
CREATE MATERIALIZED VIEW customer_spend_mv AS
SELECT o.customer_id,
sum(oi.quantity * oi.unit_price) AS spend
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY o.customer_id;
-- CONCURRENTLY refuses without a unique index — then accepts:
CREATE UNIQUE INDEX customer_spend_mv_pk ON customer_spend_mv (customer_id);
REFRESH MATERIALIZED VIEW CONCURRENTLY customer_spend_mv;
SELECT * FROM customer_spend_mv ORDER BY spend DESC;
Exercise 3: The category tree
What to do: Walk categories.parent_id with WITH RECURSIVE: every category with its level and full path.
Sample output:
level | path
-------+-----------------------
1 | Books
1 | Electronics
2 | Electronics > Laptops
2 | Electronics > Phones
1 | Home
2 | Home > Kitchen
(6 rows)
💡 Hint: anchor = parent_id IS NULL; the step joins categories to the tree built so far.
Show the solution to Exercise 3
-- Exercise 3: The category tree
WITH RECURSIVE tree AS (
SELECT category_id, name, 1 AS level, name AS path
FROM categories
WHERE parent_id IS NULL
UNION ALL
SELECT c.category_id, c.name, tree.level + 1, tree.path || ' > ' || c.name
FROM categories c
JOIN tree ON c.parent_id = tree.category_id
)
SELECT level, path FROM tree ORDER BY path;
Exercise 4: Lifetime value as a function
What to do: lifetime_value(customer_id) — non-cancelled spend, 0 for never-buyers — as a SQL function with honest volatility, then rank all six customers with it.
Sample output:
first_name | ltv
------------+---------
Meera | 2108.00
Asha | 1525.00
Ravi | 949.00
Sara | 399.00
John | 0
Vikram | 0
(6 rows)
💡 Hint: LANGUAGE sql STABLE, COALESCE for the zeros.
Show the solution to Exercise 4
-- Exercise 4: Lifetime value as a function (re-runnable)
DROP FUNCTION IF EXISTS lifetime_value(integer);
CREATE FUNCTION lifetime_value(p_customer_id integer)
RETURNS numeric
LANGUAGE sql STABLE
AS $$
SELECT COALESCE(sum(oi.quantity * oi.unit_price), 0)
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.customer_id = p_customer_id
AND o.status <> 'cancelled';
$$;
SELECT first_name, lifetime_value(customer_id) AS ltv
FROM customers
ORDER BY ltv DESC, first_name;
Exercise 5: The order badge
What to do: A PL/pgSQL function labelling an order: ≥1000 big spender, ≥500 solid, else everyday — and no such order for ghosts, total included in the label. Test orders 1, 3 and 42.
Sample output:
o1 | o3 | o42
-----------------------+-------------------+---------------
big spender (1270.00) | everyday (135.00) | no such order
(1 row)
💡 Hint: SELECT sum(...) INTO v_total leaves v_total NULL for a missing order — test that branch first.
Show the solution to Exercise 5
-- Exercise 5: The order badge (re-runnable)
DROP FUNCTION IF EXISTS order_badge(integer);
CREATE FUNCTION order_badge(p_order_id integer)
RETURNS text
LANGUAGE plpgsql STABLE
AS $$
DECLARE
v_total numeric;
BEGIN
SELECT sum(quantity * unit_price) INTO v_total
FROM order_items WHERE order_id = p_order_id;
IF v_total IS NULL THEN
RETURN 'no such order';
ELSIF v_total >= 1000 THEN
RETURN 'big spender (' || v_total || ')';
ELSIF v_total >= 500 THEN
RETURN 'solid (' || v_total || ')';
ELSE
RETURN 'everyday (' || v_total || ')';
END IF;
END;
$$;
SELECT order_badge(1) AS o1, order_badge(3) AS o3, order_badge(42) AS o42;
Exercise 6: The stock audit trigger
What to do: Audit every real stock change on products into a stock_audit table. Prove both halves: a stock update writes one audit row; an update that doesn't touch stock writes none.
Sample output:
product_id | old_stock | new_stock
------------+-----------+-----------
3 | 25 | 23
(1 row)
💡 Hint: IF NEW.stock IS DISTINCT FROM OLD.stock — Part 3's NULL-safe comparison is what makes "real change" honest.
Show the solution to Exercise 6
-- Exercise 6: The stock audit trigger (re-runnable)
DROP TRIGGER IF EXISTS trg_stock_audit ON products;
DROP FUNCTION IF EXISTS log_stock_change();
DROP TABLE IF EXISTS stock_audit;
CREATE TABLE stock_audit (
audit_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
product_id integer NOT NULL,
old_stock integer,
new_stock integer,
changed_at timestamptz NOT NULL DEFAULT now()
);
CREATE FUNCTION log_stock_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.stock IS DISTINCT FROM OLD.stock THEN
INSERT INTO stock_audit (product_id, old_stock, new_stock)
VALUES (OLD.product_id, OLD.stock, NEW.stock);
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER trg_stock_audit
AFTER UPDATE ON products
FOR EACH ROW EXECUTE FUNCTION log_stock_change();
UPDATE products SET stock = stock - 2 WHERE product_id = 3; -- fires
UPDATE products SET name = name WHERE product_id = 3; -- must NOT fire
SELECT product_id, old_stock, new_stock FROM stock_audit;
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Matview without a refresh job | Quietly ancient dashboards | Schedule REFRESH; monitor its age |
| REFRESH CONCURRENTLY, no unique index | Refused, with a hint | Create the unique index first |
| Recursive CTE on cyclic data | Infinite recursion | Depth guard or visited-set |
| Mislabelled volatility (IMMUTABLE lies) | Cached wrong answers | Label honestly; default to STABLE for readers |
| Row-by-row loops where SQL joins would do | 100× slower than the set-based form | SQL first; PL/pgSQL for genuine branching |
| Business workflow in triggers | Invisible side effects, untestable flows | Constraints + audit in DB; workflow in apps |
Quick recap
- A view is a named query: an abstraction and a security fence that costs zero storage.
- A materialized view stores its results and brings a refresh obligation; refreshing CONCURRENTLY needs a unique index.
- WITH RECURSIVE runs an anchor plus a self-referencing step until nothing new appears — and you guard it against cycles.
- SQL functions wrap reusable expressions (with honest volatility), PL/pgSQL adds real branching, and procedures do CALL-able work that controls its own transactions.
- Triggers see OLD/NEW and enforce what no app can skip — priced in invisibility.
- Integrity rules live in the database, workflow lives in the application, and all of it travels in migrations.
Checklist
Before Part 14, make sure you can:
- Wrap a four-table join in a view and query it like a table.
- Explain matview staleness and the CONCURRENTLY requirement from memory.
- Walk the full org chart (or category tree) with WITH RECURSIVE.
- Write order_total() and restock_advice() without looking.
- Build the price-audit trigger and prove it fires only on real changes.
- Argue, in three sentences, what logic belongs on which side of the boundary.
Read more: the official views and materialized views pages, the PL/pgSQL chapter, and trigger overview.