Views, functions and triggers
So far, all logic has lived in your queries. PostgreSQL can also store logic inside the database: saved queries (views), reusable functions, and triggers that run automatically when data changes. Used well, they keep rules in one place for every app that touches the data.
Views: saved queries
A view is a named query that you can select from like a table. It stores no data; it runs its query each time.
Views hide complex joins, give reports a stable interface, and can expose only some columns to certain users (see the security lesson).
Materialized views: cached results
A materialized view runs its query once and stores the result. Reads are instant, but the data is a snapshot until you refresh it:
They're ideal for dashboards and expensive reports that can be a few minutes stale. Refresh them on a schedule (for example with the pg_cron extension or a job in your app).
SQL functions
A function packages a query with parameters:
$$ … $$ is dollar quoting: a way to write a string containing quotes without escaping them. STABLE tells the planner the function doesn't modify data and returns the same result within a query, which lets it optimise.
Functions can also return whole tables:
PL/pgSQL: procedural code
When you need variables, IF, loops and error handling, use PL/pgSQL, Postgres's built-in programming language:
Because a function runs inside one transaction, the stock check, the stock update and the insert succeed or fail together.
💬 How much logic belongs in the database is a team choice. A good rule: put data-integrity logic (constraints, audit trails, "these two changes must happen together") in the database, and business workflows (emails, payments, API calls) in the app.
Triggers: run code on every change
A trigger calls a function automatically when rows are inserted, updated or deleted. Classic use #1: keep an updated_at column correct, no matter which app does the update:
Classic use #2: an audit log recording who changed what:
| Trigger timing | Use for |
|---|---|
BEFORE |
Changing or validating the row before it's written (NEW.x := …) |
AFTER |
Side effects once the change is final (audit logs, counters) |
FOR EACH ROW |
Runs once per affected row |
FOR EACH STATEMENT |
Runs once per statement, however many rows |
⚠️ Triggers are invisible when reading app code, so a teammate may not know they exist. Name them clearly, keep them small, and document them.
\d tablenamelists a table's triggers.
Procedures
A procedure is like a function that returns nothing, is run with CALL, and can COMMIT partway through, which is useful for big batch jobs:
Practice
- Create a view
customer_summarywith each customer's name, number of orders and total quantity. - Write a PL/pgSQL function
discount(price numeric, percent integer)that raises an exception if percent is above 50. - Add a trigger that prevents deleting products that still have stock (hint:
BEFORE DELETE,RAISE EXCEPTION, andRETURN OLDto allow the delete).
1.What's the difference between a view and a materialized view?
2.In a row-level trigger function, what is NEW?
3.Which trigger timing lets you modify the row before it's saved?