Log inSign up

Moving logic into PostgreSQL with views, triggers and CTEs

Wrap repeated queries in a CREATE VIEW, cache heavy reports with a materialized view and REFRESH MATERIALIZED VIEW CONCURRENTLY, and keep audit columns correct with a PL/pgSQL trigger function. For readable multi-step queries, use WITH common table expressions; for trees and graphs, WITH RECURSIVE; and for conditional output, CASE.

Topic: Databases · Tested on: Ubuntu 24.04 and 22.04, Debian 12 and 13, Rocky Linux 9, AlmaLinux 9 · Updated 2026-12-03

What sample schema do the examples use?

The examples use a tiny shop schema with customers, orders and a category tree. Run it in any test database, for instance the one from the data types guide, or create a new one with createdb as shown in installing PostgreSQL.

CREATE TABLE customers (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email      text UNIQUE NOT NULL,
  country    text NOT NULL,
  updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE sales (
  id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id bigint NOT NULL REFERENCES customers(id),
  amount      numeric(10,2) NOT NULL,
  placed_at   timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE categories (
  id        int PRIMARY KEY,
  parent_id int REFERENCES categories(id),
  name      text NOT NULL
);
INSERT INTO customers (email, country) VALUES ('ana@example.net', 'PT'), ('li@example.net', 'SG');
INSERT INTO sales (customer_id, amount) VALUES (1, 40), (1, 95.50), (2, 240);
INSERT INTO categories VALUES (1, NULL, 'Servers'), (2, 1, 'VPS'), (3, 2, 'NVMe VPS'), (4, 1, 'Storage');

How do you create and use a view?

A view is a saved query that behaves like a read-only table: it always shows current data and adds no storage.

CREATE VIEW customer_totals AS
SELECT c.id, c.email, c.country,
       count(s.id)              AS orders,
       coalesce(sum(s.amount),0) AS spent
FROM customers c
LEFT JOIN sales s ON s.customer_id = c.id
GROUP BY c.id;

SELECT * FROM customer_totals WHERE spent > 100;
GRANT SELECT ON customer_totals TO reporting;

Views make good permission boundaries: a reporting role can read the view without access to the base tables. Simple views over one table are even updatable. When you change a view's columns, use CREATE OR REPLACE VIEW for additions at the end, or drop and recreate it for other changes. Grants on roles are explained in PostgreSQL roles.

When should a view be materialized?

Materialize a view when the query is slow and slightly stale results are acceptable, such as daily revenue dashboards. The result is stored on disk and only changes when you refresh it.

CREATE MATERIALIZED VIEW daily_revenue AS
SELECT date_trunc('day', placed_at) AS day, sum(amount) AS revenue, count(*) AS orders
FROM sales GROUP BY 1;

CREATE UNIQUE INDEX daily_revenue_day ON daily_revenue (day);
REFRESH MATERIALIZED VIEW CONCURRENTLY daily_revenue;

The unique index is what allows CONCURRENTLY, so readers keep querying the old contents while the refresh runs. Schedule the refresh with a systemd timer or cron; a crontab line for the postgres user could be:

*/15 * * * * psql -d shop -qc "REFRESH MATERIALIZED VIEW CONCURRENTLY daily_revenue;"

See cron jobs for scheduling options.

How do you write a trigger in PostgreSQL?

Write a function that returns trigger, then attach it to a table with CREATE TRIGGER. This one keeps updated_at correct no matter which application changes a row.

CREATE OR REPLACE FUNCTION touch_updated_at() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  NEW.updated_at := now();
  RETURN NEW;
END;
$$;

CREATE TRIGGER customers_touch
BEFORE UPDATE ON customers
FOR EACH ROW EXECUTE FUNCTION touch_updated_at();

UPDATE customers SET country = 'ES' WHERE id = 1;
SELECT email, updated_at FROM customers;

A BEFORE trigger can change NEW before it is written; an AFTER trigger sees the final row and suits audit logs. The function body sits between $$ markers so you do not need to double every quote inside it.

How do you build an audit log with an AFTER trigger?

Record every change into a log table from an AFTER trigger, using the special variables TG_OP, OLD and NEW.

CREATE TABLE sales_audit (
  at      timestamptz DEFAULT now(),
  who     text DEFAULT current_user,
  op      text,
  old_row jsonb,
  new_row jsonb
);

CREATE OR REPLACE FUNCTION log_sales() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  INSERT INTO sales_audit (op, old_row, new_row)
  VALUES (TG_OP,
          CASE WHEN TG_OP IN ('UPDATE','DELETE') THEN to_jsonb(OLD) END,
          CASE WHEN TG_OP IN ('INSERT','UPDATE') THEN to_jsonb(NEW) END);
  RETURN NULL;
END;
$$;

CREATE TRIGGER sales_audit_trg
AFTER INSERT OR UPDATE OR DELETE ON sales
FOR EACH ROW EXECUTE FUNCTION log_sales();

Keep trigger functions short and predictable. Heavy work inside a row trigger slows every write, and a hidden trigger can puzzle the next developer, so document triggers next to your migrations. List them with \dS sales in psql, and switch one off for a bulk load with ALTER TABLE sales DISABLE TRIGGER sales_audit_trg;.

How do CTEs make complex queries readable?

A common table expression names an intermediate result with WITH, so a long query reads top to bottom as a series of steps.

WITH per_customer AS (
  SELECT customer_id, sum(amount) AS spent
  FROM sales
  WHERE placed_at >= now() - interval '90 days'
  GROUP BY customer_id
), ranked AS (
  SELECT customer_id, spent, rank() OVER (ORDER BY spent DESC) AS pos
  FROM per_customer
)
SELECT c.email, r.spent, r.pos
FROM ranked r JOIN customers c ON c.id = r.customer_id
WHERE r.pos <= 10;

Since PostgreSQL 12 the planner folds simple CTEs into the main query, so they cost nothing extra. Add MATERIALIZED after AS when you want the step computed once and reused. CTEs can also change data: WITH moved AS (DELETE FROM sales WHERE placed_at < '2025-01-01' RETURNING *) INSERT INTO sales_archive SELECT * FROM moved; archives rows in one statement, assuming an archive table with the same columns.

How do recursive queries walk a tree?

WITH RECURSIVE starts from an anchor row set and repeatedly joins back to itself until no new rows appear, which is ideal for category trees, org charts and threaded comments.

WITH RECURSIVE tree AS (
  SELECT id, parent_id, name, 1 AS depth, name::text AS path
  FROM categories WHERE parent_id IS NULL
  UNION ALL
  SELECT c.id, c.parent_id, c.name, t.depth + 1, t.path || ' / ' || c.name
  FROM categories c JOIN tree t ON c.parent_id = t.id
)
SELECT repeat('  ', depth - 1) || name AS indented, path FROM tree ORDER BY path;

Recursion also generates series and walks graphs. Guard against cycles in graph data with the CYCLE clause (PostgreSQL 14 and newer), for example CYCLE id SET is_cycle USING route after the closing parenthesis, or with a depth limit in the recursive part.

How do you use CASE for conditional results?

CASE returns different values depending on conditions, inside any expression: select lists, ORDER BY, aggregates and updates.

SELECT email, spent,
  CASE
    WHEN spent >= 200 THEN 'gold'
    WHEN spent >= 50  THEN 'silver'
    ELSE 'new'
  END AS tier
FROM customer_totals;

SELECT count(*) FILTER (WHERE amount >= 100) AS large,
       sum(CASE WHEN amount < 100 THEN amount ELSE 0 END) AS small_total
FROM sales;

The FILTER clause is often cleaner than a CASE inside an aggregate. Check how any of these queries runs with EXPLAIN ANALYZE, and if you need search across text columns next, continue with full-text search in PostgreSQL.

Plans that fit this guide

Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.

All prices
PlanFits becauseSizeMonthlyOrder from
A1-2development and small apps1 vCPU, 2 GB RAM, 50 GB NVMe$7.20/mo$43.20 for 6 months
A2-4reports and materialized views2 vCPU, 4 GB RAM, 100 GB NVMe$14.40/mo$43.20 for 3 months

Questions about PostgreSQL views, triggers and CTEs

Does a view slow queries down?

No. A regular view is expanded into the query that uses it, so the planner optimises the whole thing together. Only the underlying query itself determines speed.

How often should I refresh a materialized view?

As often as the data needs to be fresh and the refresh cost allows. With a unique index and CONCURRENTLY, refreshing every few minutes is fine for most dashboards.

Should I use EXECUTE FUNCTION or EXECUTE PROCEDURE?

Use EXECUTE FUNCTION. It is the current syntax since PostgreSQL 11; the older word still works but only for compatibility.

Are CTEs slower than subqueries?

Not in current versions. Since 12, non-recursive CTEs that are referenced once are inlined. Use MATERIALIZED or NOT MATERIALIZED to override that choice.

How do I stop a recursive query from looping forever?

Use the CYCLE clause, track visited ids in an array and skip them, or add a depth limit such as WHERE t.depth < 20 in the recursive term.