man postgres/select-pipeline

lesson 1 of 34 · Querying

How a SELECT runs, clause by clause

lib / PostgreSQL for the people who write the queries 17 mindraft

checked against: PostgreSQL 19.0

Why does this fail:

SELECT id, total * 0.9 AS discounted
FROM orders
WHERE discounted > 50;

when ORDER BY discounted works fine? Why must a condition on count(*) go in HAVING and not in WHERE? Why can’t a window function go in WHERE at all?

All three have the same answer. A SELECT is written in one order and evaluated in another. Each clause works on the rows the clause before it produced, and it can only use the names that exist at that point. Learn the order once and most of these errors stop being surprises.

The order is:

  1. FROM, with its joins: builds the input rows.
  2. WHERE: keeps the rows for which the condition is true.
  3. GROUP BY: folds the rows into groups and computes the aggregates.
  4. HAVING: keeps the groups for which the condition is true.
  5. SELECT: computes the output columns. Window functions run here, after grouping.
  6. DISTINCT: removes duplicate output rows.
  7. ORDER BY: sorts the output rows.
  8. LIMIT and OFFSET: keep a slice of the sorted rows.

A WITH clause comes before all of these, and UNION, INTERSECT and EXCEPT combine whole SELECTs between steps 6 and 7. Later lessons cover both.

This is a logical order. It defines what a query means: which names each clause can see, and which rows the result contains. It is not the order in which the server does the work. The planner may filter rows while it reads the table, stop reading a table early because of a LIMIT (for SELECT * FROM orders LIMIT 2, EXPLAIN ANALYZE shows the scan returning 2 of the 12 rows), or move a condition from HAVING down into a table scan, as long as the result is the one the logical order defines. The last section shows a real plan.

The data

Every example in this lesson uses two small tables: a coffee roaster’s customers and their orders. The data is invented.

CREATE TABLE customers (
  id   integer PRIMARY KEY,
  name text    NOT NULL,
  city text    NOT NULL
);

CREATE TABLE orders (
  id          integer PRIMARY KEY,
  customer_id integer NOT NULL REFERENCES customers,
  ordered_on  date    NOT NULL,
  status      text    NOT NULL CHECK (status IN ('paid', 'shipped', 'cancelled')),
  total       numeric(8,2) NOT NULL
);
SELECT * FROM customers ORDER BY id;
 id | name  |  city   
----+-------+---------
  1 | Ada   | Lisbon
  2 | Ben   | Porto
  3 | Chen  | Lisbon
  4 | Dara  | Braga
  5 | Eli   | Porto
  6 | Farah | Coimbra
(6 rows)
SELECT * FROM orders ORDER BY id;
 id  | customer_id | ordered_on |  status   | total 
-----+-------------+------------+-----------+-------
 101 |           1 | 2026-03-02 | shipped   | 42.00
 102 |           2 | 2026-03-02 | shipped   | 18.50
 103 |           1 | 2026-03-05 | cancelled | 60.00
 104 |           3 | 2026-03-06 | shipped   | 75.25
 105 |           2 | 2026-03-09 | paid      | 31.00
 106 |           4 | 2026-03-10 | cancelled | 12.00
 107 |           1 | 2026-03-12 | paid      | 27.50
 108 |           5 | 2026-03-13 | shipped   | 99.90
 109 |           3 | 2026-03-15 | shipped   | 23.75
 110 |           4 | 2026-03-18 | paid      | 64.00
 111 |           2 | 2026-03-20 | shipped   | 42.00
 112 |           5 | 2026-03-21 | cancelled | 15.00
(12 rows)

Each box shows the output recorded with psql. Press “run” to run the query in this page, in PGlite (PostgreSQL 19.0 compiled to WebAssembly), and “edit” to change it first. All boxes share one database, loaded from the setup script. Every box in this lesson gives the same output live as recorded, errors included.

One query, step by step

This query lists the customers with at least two orders that were not cancelled, with how much they spent, biggest spenders first, top two only:

SELECT c.name, count(*) AS orders, sum(o.total) AS spent
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
WHERE o.status <> 'cancelled'
GROUP BY c.id
HAVING count(*) >= 2
ORDER BY spent DESC
LIMIT 2;
 name | orders | spent 
------+--------+-------
 Chen |      2 | 99.00
 Ben  |      3 | 91.50
(2 rows)

Step through it one clause at a time:

Each frame is the result of a separate query that stops after that clause, run against PostgreSQL 19.0 by the lesson’s trace.py. The frames show the logical model, not what the executor holds in memory. Until ORDER BY the rows are shown sorted by id for readability; the model gives them no order.

Two things to notice. Eli’s single order of 99.90 is more than Chen’s total of 99.00, the top of the result, but Eli is gone before the sort ever happens: HAVING removed the group. And the aliases orders and spent appear only at the SELECT step. The clauses before it run without them, with one exception for GROUP BY that comes below.

WHERE cannot see SELECT’s aliases

WHERE runs at step 2. The alias discounted is created at step 5. When WHERE runs, the name does not exist yet:

SELECT id, total * 0.9 AS discounted
FROM orders
WHERE discounted > 50
ORDER BY id;
ERROR:  column "discounted" does not exist
LINE 3: WHERE discounted > 50
              ^

There are two fixes. Repeat the expression:

SELECT id, total * 0.9 AS discounted
FROM orders
WHERE total * 0.9 > 50
ORDER BY id;
 id  | discounted 
-----+------------
 103 |     54.000
 104 |     67.725
 108 |     89.910
 110 |     57.600
(4 rows)

Or compute the column in a subquery. The subquery’s output is the outer query’s FROM, so by the outer WHERE the name exists:

SELECT id, discounted
FROM (SELECT id, total * 0.9 AS discounted FROM orders) AS d
WHERE discounted > 50
ORDER BY id;
 id  | discounted 
-----+------------
 103 |     54.000
 104 |     67.725
 108 |     89.910
 110 |     57.600
(4 rows)

The choice is about readability, not speed. The planner pulls a simple subquery like this one up into the outer query, and EXPLAIN (VERBOSE) prints plans of the same shape for both versions, with total * 0.9 computed in the scan’s filter and again for its output. The subquery pays off when the expression is long or used several times.

ORDER BY can, but only by its bare name

ORDER BY runs at step 7, after SELECT, so the alias exists:

SELECT id, total * 0.9 AS discounted
FROM orders
ORDER BY discounted DESC
LIMIT 3;
 id  | discounted 
-----+------------
 108 |     89.910
 104 |     67.725
 110 |     57.600
(3 rows)

The rule has a catch. ORDER BY accepts an output column’s name only on its own. Inside an expression, every name is looked up among the input columns, the ones FROM produced, and discounted is not one of them:

SELECT id, total * 0.9 AS discounted
FROM orders
ORDER BY -discounted
LIMIT 3;
ERROR:  column "discounted" does not exist
LINE 3: ORDER BY -discounted
                  ^

The other direction works too: ORDER BY can sort by an input column that is not in the select list at all. Each output row still comes from one input row, so its total is known even though it is not printed. (DISTINCT changes that, as a later section shows.)

SELECT id
FROM orders
ORDER BY total DESC
LIMIT 3;
 id  
-----
 108
 104
 110
(3 rows)

WHERE filters rows, HAVING filters groups

WHERE runs before GROUP BY, while there are only single rows. An aggregate needs a group, so it cannot appear in WHERE:

SELECT customer_id, sum(total) AS spent
FROM orders
WHERE sum(total) > 80
GROUP BY customer_id;
ERROR:  aggregate functions are not allowed in WHERE
LINE 3: WHERE sum(total) > 80
              ^

HAVING runs after the groups exist. That is the place for a condition on an aggregate:

SELECT customer_id, sum(total) AS spent
FROM orders
GROUP BY customer_id
HAVING sum(total) > 80
ORDER BY customer_id;
 customer_id | spent  
-------------+--------
           1 | 129.50
           2 |  91.50
           3 |  99.00
           5 | 114.90
(4 rows)

HAVING still runs before SELECT, so it cannot use the alias spent either:

SELECT customer_id, sum(total) AS spent
FROM orders
GROUP BY customer_id
HAVING spent > 80
ORDER BY customer_id;
ERROR:  column "spent" does not exist
LINE 4: HAVING spent > 80
               ^

The two filters answer different questions, and using both is common. The query above counts cancelled orders in the total. Remove them with WHERE, before grouping, and the result changes: customer 1’s cancelled order of 60.00 no longer counts, and the customer drops below 80.

SELECT customer_id, sum(total) AS spent
FROM orders
WHERE status <> 'cancelled'
GROUP BY customer_id
HAVING sum(total) > 80
ORDER BY customer_id;
 customer_id | spent 
-------------+-------
           2 | 91.50
           3 | 99.00
           5 | 99.90
(3 rows)

A rule of thumb: a condition about one row goes in WHERE; a condition about a group goes in HAVING.

What SELECT may mention after GROUP BY

After GROUP BY, a row is a group. A column that was not grouped has many values in the group, and SELECT has to say which one it wants:

SELECT customer_id, status, count(*) AS orders
FROM orders
GROUP BY customer_id;
ERROR:  column "orders.status" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT customer_id, status, count(*) AS orders
                            ^

Either group by status too, or wrap it in an aggregate. One exception: when you group by a table’s primary key, PostgreSQL knows every other column of that table has one value per group, so you can select them directly. The step-through query relies on this: it groups by c.id and selects c.name.

SELECT c.id, c.name, c.city, count(*) AS orders
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id
ORDER BY c.id;
 id | name |  city  | orders 
----+------+--------+--------
  1 | Ada  | Lisbon |      3
  2 | Ben  | Porto  |      3
  3 | Chen | Lisbon |      2
  4 | Dara | Braga  |      2
  5 | Eli  | Porto  |      2
(5 rows)

GROUP BY and output names: an exception with a trap

By the logical order, GROUP BY should not see output aliases either. PostgreSQL accepts them anyway, as an extension to the SQL standard:

SELECT to_char(ordered_on, 'IYYY-"W"IW') AS week, count(*) AS orders
FROM orders
GROUP BY week
ORDER BY week;
   week   | orders 
----------+--------
 2026-W10 |      4
 2026-W11 |      5
 2026-W12 |      3
(3 rows)

The trap is a name that is both an alias and an input column. GROUP BY then picks the input column, and ORDER BY picks the output column. Here the alias status folds paid and shipped into active, but the grouping uses the table’s status, so there are two active rows:

SELECT CASE WHEN status = 'cancelled' THEN 'cancelled' ELSE 'active' END AS status,
       count(*) AS orders
FROM orders
GROUP BY status
ORDER BY status;
  status   | orders 
-----------+--------
 active    |      3
 active    |      6
 cancelled |      3
(3 rows)

ORDER BY did use the alias. Sorted by the table’s status, the cancelled group would come first, since cancelled sorts before paid and shipped; sorted by the output column, active comes first. Give the alias a name no input column has, and the grouping does what was meant:

SELECT CASE WHEN status = 'cancelled' THEN 'cancelled' ELSE 'active' END AS state,
       count(*) AS orders
FROM orders
GROUP BY state
ORDER BY state;
   state   | orders 
-----------+--------
 active    |      9
 cancelled |      3
(2 rows)

Window functions run after GROUP BY

A window function computes a value for each row from a set of related rows, such as a rank within a partition. It runs at step 5, with the rest of the select list. WHERE has finished long before, so a window function cannot be used there:

SELECT id, customer_id, total
FROM orders
WHERE rank() OVER (PARTITION BY customer_id ORDER BY total DESC) = 1;
ERROR:  window functions are not allowed in WHERE
LINE 3: WHERE rank() OVER (PARTITION BY customer_id ORDER BY total D...
              ^

PostgreSQL 19 has no QUALIFY clause, which some other databases add for exactly this. The fix is a subquery: compute the rank in the inner query and filter on it in the outer one. This lists each customer’s largest order:

SELECT customer_id, id, total
FROM (SELECT id, customer_id, total,
             rank() OVER (PARTITION BY customer_id ORDER BY total DESC) AS rnk
      FROM orders) AS ranked
WHERE rnk = 1
ORDER BY customer_id;
 customer_id | id  | total 
-------------+-----+-------
           1 | 103 | 60.00
           2 | 111 | 42.00
           3 | 104 | 75.25
           4 | 110 | 64.00
           5 | 108 | 99.90
(5 rows)

Running after GROUP BY also means a window function sees the groups, not the original rows. It can even take an aggregate as its argument. sum(sum(total)) OVER () adds up the per-customer sums over all groups, which gives each customer’s share of the total:

SELECT customer_id, sum(total) AS spent,
       round(100 * sum(total) / sum(sum(total)) OVER (), 1) AS pct
FROM orders
WHERE status <> 'cancelled'
GROUP BY customer_id
ORDER BY customer_id;
 customer_id | spent | pct  
-------------+-------+------
           1 | 69.50 | 16.4
           2 | 91.50 | 21.6
           3 | 99.00 | 23.4
           4 | 64.00 | 15.1
           5 | 99.90 | 23.6
(5 rows)

DISTINCT runs before ORDER BY

DISTINCT works on the output rows, after SELECT. Once duplicates are merged, a column that is not in the output has no single value per row, so ORDER BY cannot sort by it. Without DISTINCT, sorting by a column you don’t select works (the ORDER BY total example above); with it, PostgreSQL refuses:

SELECT DISTINCT city
FROM customers
ORDER BY name;
ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 3: ORDER BY name;
                 ^

PostgreSQL also has DISTINCT ON, and it is an exception to the order. It keeps the first row of each set of rows with equal values in the listed expressions, and “first” is decided by ORDER BY, which must start with the same expressions (PostgreSQL rejects the query otherwise). So with DISTINCT ON the rows are sorted first, and then the first row of each set is kept. This finds each customer’s most recent order:

SELECT DISTINCT ON (customer_id) customer_id, id AS latest_order, total
FROM orders
ORDER BY customer_id, ordered_on DESC;
 customer_id | latest_order | total 
-------------+--------------+-------
           1 |          107 | 27.50
           2 |          111 | 42.00
           3 |          109 | 23.75
           4 |          110 | 64.00
           5 |          112 | 15.00
(5 rows)

LIMIT comes last

LIMIT keeps the first N rows of whatever ORDER BY produced. Without ORDER BY there is no “first”: the rows come in whatever order the plan produces them, and that order can change between runs.

With ORDER BY, LIMIT can still cut through a tie. Orders 101 and 111 both total 42.00, and only one of them fits in the top four:

SELECT id, total
FROM orders
WHERE status <> 'cancelled'
ORDER BY total DESC
LIMIT 4;
 id  | total 
-----+-------
 108 | 99.90
 104 | 75.25
 110 | 64.00
 101 | 42.00
(4 rows)

Which of the two you get is not defined, and a live run may show the other one. Add a tiebreaker such as ORDER BY total DESC, id to fix the choice, or ask for every row that ties with the last one, with the standard FETCH syntax:

SELECT id, total
FROM orders
WHERE status <> 'cancelled'
ORDER BY total DESC
FETCH FIRST 4 ROWS WITH TIES;
 id  | total 
-----+-------
 108 | 99.90
 104 | 75.25
 110 | 64.00
 101 | 42.00
 111 | 42.00
(5 rows)

The logical order is not the plan

EXPLAIN shows what the server actually runs. Here is the step-through query again. COSTS OFF hides the cost estimates, which are not the point here:

EXPLAIN (COSTS OFF)
SELECT c.name, count(*) AS orders, sum(o.total) AS spent
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
WHERE o.status <> 'cancelled'
GROUP BY c.id
HAVING count(*) >= 2
ORDER BY spent DESC
LIMIT 2;
                           QUERY PLAN                            
-----------------------------------------------------------------
 Limit
   ->  Sort
         Sort Key: (sum(o.total)) DESC
         ->  HashAggregate
               Group Key: c.id
               Filter: (count(*) >= 2)
               ->  Hash Join
                     Hash Cond: (o.customer_id = c.id)
                     ->  Seq Scan on orders o
                           Filter: (status <> 'cancelled'::text)
                     ->  Hash
                           ->  Seq Scan on customers c
(12 rows)

A plan is a tree; read it from the innermost lines out. The clauses are all there, but not as separate passes. The WHERE condition is a Filter on the scan of orders, applied as each row is read. GROUP BY became a hash aggregate, and HAVING is a Filter on it. The sort and the limit sit on top.

The planner also moves conditions when the result stays the same. A HAVING condition that uses no aggregate, here on the grouped column city, gives the same result as a WHERE condition, and the plan applies it to the customers scan, before the join and the grouping:

EXPLAIN (COSTS OFF)
SELECT c.city, count(*) AS orders
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.city
HAVING c.city = 'Lisbon';
                     QUERY PLAN                      
-----------------------------------------------------
 GroupAggregate
   ->  Hash Join
         Hash Cond: (o.customer_id = c.id)
         ->  Seq Scan on orders o
         ->  Hash
               ->  Seq Scan on customers c
                     Filter: (city = 'Lisbon'::text)
(7 rows)

So: use the logical order to reason about what a query means and which names it can use, and EXPLAIN to see what it costs. The plans above were recorded with psql against a native PostgreSQL 19.0 server on tables that were never analyzed. PGlite printed the same two plans when this lesson was checked; with other settings or table statistics, a plan can differ. The lesson on EXPLAIN covers reading plans in full.

Try it yourself

Use the boxes above: press “edit”, change the query, press “run”.

  1. In the step-through query (the first box after “One query, step by step”), change the WHERE condition to o.status = 'shipped'. Before you run it, use the figure to predict which customers are left.
  2. In the same query, move o.status <> 'cancelled' from WHERE to HAVING. What happens, and why?
  3. List the customers whose largest non-cancelled order is more than half of everything they spent on non-cancelled orders.
  4. Find each customer’s second most recent order.
  5. Make the LIMIT 4 query return the same rows every time.

Answers

  1. Chen (orders 104 and 109) and Ben (102 and 111), in that order. Dara has no shipped order and is gone after WHERE. Ada and Eli have one shipped order each (Ada’s order 107 is only paid), so HAVING drops them.

  2. It fails. After GROUP BY, o.status has many values per group, and HAVING can only use grouped columns and aggregates:

SELECT c.name, count(*) AS orders, sum(o.total) AS spent
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id
HAVING count(*) >= 2 AND o.status <> 'cancelled'
ORDER BY spent DESC
LIMIT 2;
ERROR:  column "o.status" must appear in the GROUP BY clause or be used in an aggregate function
LINE 5: HAVING count(*) >= 2 AND o.status <> 'cancelled'
                                 ^
  1. Both conditions are about the group, so both aggregates go in HAVING:
SELECT customer_id, max(total) AS largest, sum(total) AS spent
FROM orders
WHERE status <> 'cancelled'
GROUP BY customer_id
HAVING max(total) > sum(total) / 2
ORDER BY customer_id;
 customer_id | largest | spent 
-------------+---------+-------
           1 |   42.00 | 69.50
           3 |   75.25 | 99.00
           4 |   64.00 | 64.00
           5 |   99.90 | 99.90
(4 rows)
  1. Number the orders per customer in a subquery, then filter on the number outside it. Every customer with orders has at least two, so five rows come back:
SELECT customer_id, id, total
FROM (SELECT id, customer_id, total,
             row_number() OVER (PARTITION BY customer_id
                                ORDER BY ordered_on DESC) AS n
      FROM orders) AS numbered
WHERE n = 2
ORDER BY customer_id;
 customer_id | id  | total 
-------------+-----+-------
           1 | 103 | 60.00
           2 | 105 | 31.00
           3 | 104 | 75.25
           4 | 106 | 12.00
           5 | 108 | 99.90
(5 rows)
  1. Add id to the ORDER BY, after total DESC. The sort key is then unique, so the fourth row is always the same one.

Sources

The PostgreSQL 19 documentation:

ls postgres/

Querying

  • 01 How a SELECT runs, clause by clause draftThe logical order of FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY and LIMIT, and the everyday errors it explains.
  • 02 Tables and the types worth knowing draftinteger and bigint, numeric against double precision, text, boolean, uuid (including uuidv7), identity columns, and casts.
  • 03 NULL and three-valued logic draftWhy x = NULL is never true, IS DISTINCT FROM, coalesce, NOT IN with a NULL in the list, and how aggregates skip NULLs.
  • 04 Joins draftInner, left, right, full and cross joins; ON against USING; semi- and anti-joins with EXISTS; the rows an outer join adds.
  • 05 Aggregates and GROUP BY plannedcount(*) against count(x), FILTER, ordered string_agg and array_agg, any_value, and grouping by a primary key.
  • 06 Subqueries and set operations plannedScalar, IN, EXISTS, ANY and ALL subqueries, correlated subqueries, and UNION, INTERSECT and EXCEPT with and without ALL.
  • 07 Sorting and paging plannedNULLS FIRST and LAST, collations, ties and FETCH ... WITH TIES, and keyset pagination instead of large OFFSETs.
  • 08 Dates, times and time zones plannedtimestamp against timestamptz, the session time zone, intervals, date_trunc, and generate_series for calendars.
  • 09 Changing data plannedINSERT, UPDATE and DELETE with RETURNING, including OLD and NEW values in RETURNING, and UPDATE ... FROM.

Analytical queries

  • 10 Window functions plannedPARTITION BY, ORDER BY and frames; ranking, running totals and moving averages; lag, lead and first_value with IGNORE NULLS.
  • 11 WITH queries plannedCommon table expressions for readability, MATERIALIZED and NOT MATERIALIZED, and data-modifying statements in WITH.
  • 12 Recursive queries plannedWITH RECURSIVE over trees and graphs, the SEARCH and CYCLE clauses, and how to stop a recursion that never ends.
  • 13 LATERAL plannedSubqueries and functions that see the row beside them: top N per group, and set-returning functions per row.
  • 14 GROUPING SETS, ROLLUP and CUBE plannedSeveral groupings in one query, subtotals and grand totals, and telling them apart with GROUPING().

Richer data

  • 15 JSONB plannedOperators, containment, jsonpath, updating documents, and the GIN indexes that make the queries fast.
  • 16 SQL/JSON and JSON_TABLE plannedThe standard JSON functions: JSON_VALUE, JSON_QUERY, JSON_EXISTS, IS JSON, and JSON_TABLE to turn documents into rows.
  • 17 Arrays plannedBuilding and slicing arrays, unnest WITH ORDINALITY, = ANY, array_agg, array_sort, and when a table is better.
  • 18 Ranges and temporal keys plannedRange and multirange types, overlap and containment, exclusion constraints, and primary keys WITHOUT OVERLAPS.
  • 19 Full-text search plannedtsvector and tsquery, configurations and dictionaries, ranking, highlighting, and indexing a search column.

Keeping data correct

  • 20 Constraints plannedCHECK, NOT NULL, UNIQUE with NULLS NOT DISTINCT, foreign keys and their actions, deferrable constraints, NOT VALID.
  • 21 Generated columns plannedColumns computed from others, virtual (the default) or stored, and what each costs on reads and writes.
  • 22 Transactions and isolation levels plannedWhat READ COMMITTED, REPEATABLE READ and SERIALIZABLE let two sessions see, the anomalies each allows, and retrying serialization failures.
  • 23 Row locks and queues plannedSELECT ... FOR UPDATE and its weaker forms, NOWAIT, SKIP LOCKED for job queues, and advisory locks.
  • 24 Upsert and MERGE plannedINSERT ... ON CONFLICT DO NOTHING, DO UPDATE and DO SELECT; MERGE with WHEN NOT MATCHED BY SOURCE and RETURNING merge_action().

Performance from the query side

  • 25 Indexes plannedWhat a B-tree index can answer: column order in multicolumn indexes, partial, expression and covering (INCLUDE) indexes.
  • 26 GIN, GiST, BRIN and hash plannedWhich queries each index type serves, with the operators that use it: containment, overlap, nearest neighbour, ranges of a big table.
  • 27 Reading EXPLAIN plannedPlan nodes, estimated against actual rows, buffers, and the questions to ask of a slow plan. How statistics feed the estimates.
  • 28 Partitioning plannedRange, list and hash partitions, partition pruning in plans, and attaching and detaching partitions.

Logic and access in the database

  • 29 Views and materialized views plannedNaming a query, updatable views, WITH CHECK OPTION, and refreshing a materialized view concurrently.
  • 30 SQL and PL/pgSQL functions plannedFunctions and procedures, volatility, set-returning functions, and PL/pgSQL control flow and error handling.
  • 31 Triggers plannedRow and statement triggers, BEFORE and AFTER, transition tables, and keeping an audit log.
  • 32 LISTEN and NOTIFY plannedMessages between sessions, how they interact with transactions, and a small change feed.
  • 33 Row-level security plannedPolicies that filter rows per role, USING against WITH CHECK, and the roles that bypass them.
  • 34 Extensions worth knowing plannedpg_trgm, pgcrypto, citext, btree_gist, postgres_fdw and pg_stat_statements: what each adds and when to reach for it.