man postgres/subqueries-and-set-operations

lesson 6 of 34 · Querying

Subqueries and set operations

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

checked against: PostgreSQL 19.0

This query shows each customer’s paid order, if they have one:

SELECT c.name,
       (SELECT o.id FROM orders AS o
        WHERE o.customer_id = c.id AND o.status = 'paid') AS paid_order
FROM customers AS c
ORDER BY c.id;
 name  | paid_order 
-------+------------
 Ada   |        107
 Ben   |        105
 Chen  |           
 Dara  |        110
 Eli   |           
 Farah |           
(6 rows)

It works, and it will keep working until some customer has two paid orders. The same query for shipped orders fails at once, because Ben and Chen have two each:

SELECT c.name,
       (SELECT o.id FROM orders AS o
        WHERE o.customer_id = c.id AND o.status = 'shipped') AS shipped_order
FROM customers AS c
ORDER BY c.id;
ERROR:  more than one row returned by a subquery used as an expression

A subquery in parentheses, used where a value is expected, is a scalar subquery. It must return one column and at most one row. The row count is checked while the query runs, row by row, so the first query is correct only because of the data it happens to meet. This lesson goes through the kinds of subquery and what each one promises: scalar subqueries, IN, ANY, ALL and EXISTS, and subqueries that refer to the outer row. The second half is about combining whole queries with UNION, INTERSECT and EXCEPT.

The data

The customers, orders and shipping zones of the lesson on joins, unchanged. The data is in the setup script.

SELECT id, name, city, referred_by FROM customers ORDER BY id;
 id | name  |  city   | referred_by 
----+-------+---------+-------------
  1 | Ada   | Lisbon  |            
  2 | Ben   | Porto   |           1
  3 | Chen  | Lisbon  |           1
  4 | Dara  | Braga   |            
  5 | Eli   | Porto   |           3
  6 | Farah | Coimbra |            
(6 rows)
SELECT id, customer_id, status, total FROM orders ORDER BY id;
 id  | customer_id |  status   | total 
-----+-------------+-----------+-------
 101 |           1 | shipped   | 42.00
 102 |           2 | shipped   | 18.50
 103 |           1 | cancelled | 60.00
 104 |           3 | shipped   | 75.25
 105 |           2 | paid      | 31.00
 106 |           4 | cancelled | 12.00
 107 |           1 | paid      | 27.50
 108 |           5 | shipped   | 99.90
 109 |           3 | shipped   | 23.75
 110 |           4 | paid      | 64.00
 111 |           2 | shipped   | 42.00
 112 |           5 | cancelled | 15.00
(12 rows)
SELECT * FROM shipping_zones ORDER BY city;
  city  | zone | fee  
--------+------+------
 Faro   | B    | 5.00
 Lisbon | A    | 3.50
 Porto  | A    | 3.50
(3 rows)

Every box on this page gives the same output live as recorded.

Scalar subqueries

A scalar subquery stands for one value, so it can go wherever a value can: in the select list, in WHERE, in ORDER BY, as a function’s argument. Three rules come with it.

It returns NULL when it finds no row. That is why Chen, Eli and Farah have an empty paid_order above instead of disappearing.

It must not return more than one row, and the error is raised only when one does, as the opener showed. When “the” row is not unique, say which one you want: an aggregate (max(o.id)) or an ORDER BY with LIMIT 1 both return at most one row whatever the data.

SELECT c.name,
       (SELECT o.id FROM orders AS o
        WHERE o.customer_id = c.id AND o.status = 'shipped'
        ORDER BY o.ordered_on DESC, o.id DESC
        LIMIT 1) AS last_shipped
FROM customers AS c
ORDER BY c.id;
 name  | last_shipped 
-------+--------------
 Ada   |          101
 Ben   |          111
 Chen  |          109
 Dara  |             
 Eli   |          108
 Farah |             
(6 rows)

And it must return exactly one column. This rule is checked before the query runs:

SELECT c.name,
       (SELECT o.id, o.total FROM orders AS o
        WHERE o.customer_id = c.id
        ORDER BY o.id LIMIT 1) AS first_order
FROM customers AS c;
ERROR:  subquery must return only one column
LINE 2:        (SELECT o.id, o.total FROM orders AS o
               ^

A subquery that does not mention the outer query has the same value for every row. “Orders above the average order” compares each total with one number:

SELECT id, total, (SELECT avg(total) FROM orders) AS average
FROM orders
WHERE total > (SELECT avg(total) FROM orders)
ORDER BY id;
 id  | total |       average       
-----+-------+---------------------
 103 | 60.00 | 42.5750000000000000
 104 | 75.25 | 42.5750000000000000
 108 | 99.90 | 42.5750000000000000
 110 | 64.00 | 42.5750000000000000
(4 rows)

The two orders of exactly 42.00 are just below the average. A subquery like this needs to be computed only once, and in the plan for this query it is: EXPLAIN shows it as an InitPlan, a part of the plan that is computed once and whose value the filter then uses.

EXPLAIN (COSTS OFF)
SELECT id, total
FROM orders
WHERE total > (SELECT avg(total) FROM orders);
                 QUERY PLAN                 
--------------------------------------------
 Seq Scan on orders
   Filter: (total > (InitPlan expr_1).col1)
   InitPlan expr_1
     ->  Aggregate
           ->  Seq Scan on orders orders_1
(5 rows)

Correlated subqueries

The subqueries in the opener are different: they mention c.id, a column of the outer query. A subquery that refers to the outer row is correlated, and its meaning is that it is evaluated again for each outer row, with that row’s values filled in. “Orders above their own customer’s average” needs one:

SELECT o.id, o.customer_id, o.total
FROM orders AS o
WHERE o.total > (SELECT avg(i.total)
                 FROM orders AS i
                 WHERE i.customer_id = o.customer_id)
ORDER BY o.id;
 id  | customer_id | total 
-----+-------------+-------
 103 |           1 | 60.00
 104 |           3 | 75.25
 105 |           2 | 31.00
 108 |           5 | 99.90
 110 |           4 | 64.00
 111 |           2 | 42.00
(6 rows)

The two aliases matter. orders appears twice, as o for the order being tested and as i for the orders it is compared with. Without them, customer_id = customer_id inside the subquery would compare the inner row’s column with itself, since an unqualified name is looked up in the nearest query first. Step through the outer rows:

For each outer row, the subquery was run against PostgreSQL 19.0 with that row’s customer_id in place of o.customer_id, by the lesson’s trace.py, and the rows kept are checked against the real query. This is what a correlated subquery means; the planner is free to compute the same result another way.

In this case the plan does run the subquery once per outer row. EXPLAIN ANALYZE, with the timing and cost details turned off, shows it as a SubPlan with loops=12:

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT o.id, o.customer_id, o.total
FROM orders AS o
WHERE o.total > (SELECT avg(i.total)
                 FROM orders AS i
                 WHERE i.customer_id = o.customer_id);
                           QUERY PLAN                           
----------------------------------------------------------------
 Seq Scan on orders o (actual rows=6.00 loops=1)
   Filter: (total > (SubPlan expr_1))
   Rows Removed by Filter: 6
   SubPlan expr_1
     ->  Aggregate (actual rows=1.00 loops=12)
           ->  Seq Scan on orders i (actual rows=2.50 loops=12)
                 Filter: (customer_id = o.customer_id)
                 Rows Removed by Filter: 10
(8 rows)

Twelve scans of a table of twelve rows cost nothing. Twelve thousand outer rows, each scanning a big table without an index, would. The same question written as a join to a grouped subquery computes each customer’s average once:

SELECT o.id, o.customer_id, o.total
FROM orders AS o
JOIN (SELECT customer_id, avg(total) AS avg_total
      FROM orders
      GROUP BY customer_id) AS a ON a.customer_id = o.customer_id
WHERE o.total > a.avg_total
ORDER BY o.id;
 id  | customer_id | total 
-----+-------------+-------
 103 |           1 | 60.00
 104 |           3 | 75.25
 105 |           2 | 31.00
 108 |           5 | 99.90
 110 |           4 | 64.00
 111 |           2 | 42.00
(6 rows)

Neither form is always faster; the correlated one can be cheap when an index serves the inner WHERE and few outer rows reach it. Write the form that reads better, and check the plan when it matters. The lesson on window functions shows a third way, avg(total) OVER (PARTITION BY customer_id).

IN and NOT IN with a subquery

x IN (SELECT ...) is true when the subquery returns a row equal to x. The subquery returns a column of values, any number of them, so there is no one-row rule. The lesson on NULL showed the trap in its negation: if the subquery returns a NULL, NOT IN is never true, and the query quietly returns nothing.

The same rule shows in the plans. When neither side of the comparison can be NULL, as customers.id (a primary key) and orders.customer_id (declared NOT NULL) cannot, PostgreSQL 19 can run NOT IN as an anti-join, the kind of plan the lesson on joins showed for NOT EXISTS:

EXPLAIN (COSTS OFF)
SELECT name FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders);
                    QUERY PLAN                    
--------------------------------------------------
 Hash Right Anti Join
   Hash Cond: (orders.customer_id = customers.id)
   ->  Seq Scan on orders
   ->  Hash
         ->  Seq Scan on customers
(5 rows)

When either side can be NULL, it cannot: an anti-join would return rows that NOT IN must not return. In these two plans, one with a nullable column in the subquery and one with a nullable column on the left, the subquery became a hashed SubPlan, tested for each customer:

EXPLAIN (COSTS OFF)
SELECT name FROM customers
WHERE id NOT IN (SELECT referred_by FROM customers);
                        QUERY PLAN                        
----------------------------------------------------------
 Seq Scan on customers
   Filter: (NOT (ANY (id = (hashed SubPlan any_1).col1)))
   SubPlan any_1
     ->  Seq Scan on customers customers_1
(4 rows)
EXPLAIN (COSTS OFF)
SELECT name FROM customers
WHERE referred_by NOT IN (SELECT customer_id FROM orders);
                            QUERY PLAN                             
-------------------------------------------------------------------
 Seq Scan on customers
   Filter: (NOT (ANY (referred_by = (hashed SubPlan any_1).col1)))
   SubPlan any_1
     ->  Seq Scan on orders
(4 rows)

All three plans were recorded on tables that were never analyzed, and PGlite printed the same ones when the lesson was checked. The advice from the lesson on NULL stands: NOT EXISTS means what it says whatever the column allows.

ANY and ALL

IN tests equality. ANY and ALL generalise it to any comparison operator: x > ANY (subquery) is true if x is greater than at least one of the values, and x > ALL (subquery) if it is greater than every one of them. = ANY is the same as IN, and <> ALL is the same as NOT IN, NULL trap included. SOME is another spelling of ANY.

Which orders are larger than every order of Ben’s?

SELECT id, customer_id, total
FROM orders
WHERE total > ALL (SELECT total FROM orders WHERE customer_id = 2)
ORDER BY id;
 id  | customer_id | total 
-----+-------------+-------
 103 |           1 | 60.00
 104 |           3 | 75.25
 108 |           5 | 99.90
 110 |           4 | 64.00
(4 rows)

Ben’s largest order is 42.00, and total is never NULL, so this is the same as total > (SELECT max(total) ...), with one difference that matters: what happens when the subquery returns nothing. Farah has no orders. “Larger than every one of Farah’s orders” is true of every order, because there is no order of hers to fail the test, while “larger than at least one” is true of none:

SELECT count(*) FILTER (WHERE total > ALL (SELECT total FROM orders WHERE customer_id = 6)) AS gt_all,
       count(*) FILTER (WHERE total > ANY (SELECT total FROM orders WHERE customer_id = 6)) AS gt_any,
       count(*) FILTER (WHERE total > (SELECT max(total) FROM orders WHERE customer_id = 6)) AS gt_max
FROM orders;
 gt_all | gt_any | gt_max 
--------+--------+--------
     12 |      0 |      0
(1 row)

ALL over an empty set is true, ANY over an empty set is false, and the max version compares with NULL and keeps nothing. Each is right for some question; make sure it is the one you are asking.

NULLs follow the rules of the lesson on NULL. A NULL in the list makes ALL unknown unless some value already fails the test, and makes ANY unknown unless some value already passes it:

SELECT 50 > ALL (VALUES (10), (NULL)) AS a,
       5  > ALL (VALUES (10), (NULL)) AS b,
       50 > ANY (VALUES (10), (NULL)) AS c,
       5  > ANY (VALUES (10), (NULL)) AS d;
 a | b | c | d 
---+---+---+---
   | f | t | 
(1 row)

ANY and ALL also take an array instead of a subquery. That is the usual way to pass a list as one query parameter: WHERE status = ANY ($1), with the application sending an array.

SELECT id, status
FROM orders
WHERE status = ANY ('{paid,cancelled}'::text[])
ORDER BY id;
 id  |  status   
-----+-----------
 103 | cancelled
 105 | paid
 106 | cancelled
 107 | paid
 110 | paid
 112 | cancelled
(6 rows)

Comparing several columns at once

The left side of IN can be a row: (a, b) IN (SELECT x, y ...) matches when both columns match the same subquery row. Each customer’s most recent order is the order whose customer and date appear among the per-customer maximums:

SELECT customer_id, id, ordered_on, total
FROM orders
WHERE (customer_id, ordered_on) IN (SELECT customer_id, max(ordered_on)
                                    FROM orders
                                    GROUP BY customer_id)
ORDER BY customer_id;
 customer_id | id  | ordered_on | total 
-------------+-----+------------+-------
           1 | 107 | 2026-03-12 | 27.50
           2 | 111 | 2026-03-20 | 42.00
           3 | 109 | 2026-03-15 | 23.75
           4 | 110 | 2026-03-18 | 64.00
           5 | 112 | 2026-03-21 | 15.00
(5 rows)

Unlike DISTINCT ON in the first lesson, this returns every order that ties for a customer’s latest date. None does here.

EXISTS

EXISTS, from the lesson on joins, is the subquery form that only asks whether a row exists. It is nearly always correlated, it ignores what the subquery selects, and it is true or false, never NULL. Of the subquery tests in this lesson it is the one whose meaning does not depend on NULLs or on how many rows match, which is why it is the safe default for “has a” and “has no” questions.

Combining queries: UNION, INTERSECT, EXCEPT

A subquery puts one query inside another. The set operations put two queries side by side and combine their rows. The cities that have customers, and the cities that have a shipping zone:

SELECT city FROM customers
UNION
SELECT city FROM shipping_zones
ORDER BY city;
  city   
---------
 Braga
 Coimbra
 Faro
 Lisbon
 Porto
(5 rows)

UNION returns the rows that are in either result, each distinct row once. It removes duplicates within each side too: Lisbon has two customers and appears once. UNION ALL keeps every row of both sides and does no duplicate removal, which makes it the cheaper of the two when duplicates can’t occur or don’t matter.

SELECT city FROM customers
INTERSECT
SELECT city FROM shipping_zones
ORDER BY city;
  city  
--------
 Lisbon
 Porto
(2 rows)
SELECT city FROM customers
EXCEPT
SELECT city FROM shipping_zones
ORDER BY city;
  city   
---------
 Braga
 Coimbra
(2 rows)

INTERSECT returns the rows that are in both: the cities with customers and a zone. EXCEPT returns the rows of the left side that are not in the right: the cities with customers but no zone. EXCEPT is not symmetric: with the sides swapped, it returns the zones that have no customers.

With ALL: counting copies

Without ALL, all three treat each side as a set: a row is in it or not. With ALL they count copies. If a row appears m times on the left and n times on the right, UNION ALL returns it m + n times, INTERSECT ALL min(m, n) times, and EXCEPT ALL max(m − n, 0) times. Lisbon and Porto have two customers each and one zone each:

SELECT city FROM customers
INTERSECT ALL
SELECT city FROM shipping_zones
ORDER BY city;
  city  
--------
 Lisbon
 Porto
(2 rows)
SELECT city FROM customers
EXCEPT ALL
SELECT city FROM shipping_zones
ORDER BY city;
  city   
---------
 Braga
 Coimbra
 Lisbon
 Porto
(4 rows)

INTERSECT ALL keeps one Lisbon and one Porto, the copies both sides have. EXCEPT ALL subtracts one copy of each from the customers’ two, so one Lisbon and one Porto remain, next to Braga and Coimbra.

The rules

The two sides must return the same number of columns, matched by position, and each pair of columns must have types that can be resolved to one:

SELECT city, name FROM customers
UNION
SELECT city FROM shipping_zones;
ERROR:  each UNION query must have the same number of columns
LINE 3: SELECT city FROM shipping_zones;
               ^
SELECT city FROM customers
UNION
SELECT id FROM customers;
ERROR:  UNION types text and integer cannot be matched
LINE 3: SELECT id FROM customers;
               ^

The column names come from the first query. An ORDER BY or LIMIT at the end applies to the combined result, not to the last query, and its ORDER BY can only name output columns (or their positions), not expressions:

SELECT city FROM customers
UNION
SELECT city FROM shipping_zones
ORDER BY lower(city);
ERROR:  invalid UNION/INTERSECT/EXCEPT ORDER BY clause
LINE 4: ORDER BY lower(city);
                 ^
DETAIL:  Only result column names can be used, not expressions or functions.
HINT:  Add the expression/function to every SELECT, or move the UNION into a FROM clause.

The HINT gives both ways out: compute lower(city) as an output column on every side, or make the UNION a subquery in FROM and sort its rows outside. To sort or limit one side on its own, put that side in parentheses.

When a statement chains several set operations, INTERSECT is applied before UNION and EXCEPT, the way * is applied before +; UNION and EXCEPT are applied from left to right. Parentheses make the grouping explicit:

SELECT 'Aveiro' AS city
UNION
SELECT city FROM customers
INTERSECT
SELECT city FROM shipping_zones
ORDER BY city;
  city  
--------
 Aveiro
 Lisbon
 Porto
(3 rows)
(SELECT 'Aveiro' AS city
 UNION
 SELECT city FROM customers)
INTERSECT
SELECT city FROM shipping_zones
ORDER BY city;
  city  
--------
 Lisbon
 Porto
(2 rows)

The first computes the INTERSECT first (Lisbon, Porto) and then adds Aveiro. The second adds Aveiro to the customers’ cities and then intersects with the zones, which have no Aveiro.

NULLs are equal here

Set operations compare whole rows the way DISTINCT does, so two NULLs count as the same value. An = comparison never matches a NULL, but INTERSECT does:

SELECT email FROM customers
INTERSECT
SELECT NULL::text;
 email 
-------
 
(1 row)

One row, holding NULL: two customers have no email, and the NULL on the right matched them. The same question as WHERE email IN (NULL) returns no rows.

That makes EXCEPT a different tool from NOT EXISTS. EXCEPT compares entire rows, treats NULLs as equal and removes duplicates from the result; NOT EXISTS tests a condition you write, and keeps the outer rows as they are, duplicates included. Use EXCEPT to compare two results column for column, as in “which rows of yesterday’s export are missing today”, and NOT EXISTS to filter one table by another.

Try it yourself

Use any box above: press “edit”, replace the query, press “run”. The queries in the answers can be pasted the same way.

  1. For each customer, show the total of their largest order, and 0 for a customer without orders, using a scalar subquery.
Answer

max returns at most one row, so the subquery is safe whatever the data, and coalesce turns Farah’s NULL into 0:

SELECT c.name,
       coalesce((SELECT max(o.total) FROM orders AS o WHERE o.customer_id = c.id), 0) AS largest
FROM customers AS c
ORDER BY c.id;
  1. List the orders whose total is larger than every order of a customer in Lisbon. Then change the city to 'Faro' and explain the result.
Answer

For Lisbon, only order 108 (99.90) beats Ada’s and Chen’s orders, the largest of which is 75.25:

SELECT id, total
FROM orders
WHERE total > ALL (SELECT o.total
                   FROM orders AS o
                   JOIN customers AS c ON c.id = o.customer_id
                   WHERE c.city = 'Lisbon')
ORDER BY id;

With 'Faro' every order comes back: nobody in Faro has ordered, the subquery is empty, and ALL over an empty set is true. Counted:

SELECT count(*) AS orders
FROM orders
WHERE total > ALL (SELECT o.total
                   FROM orders AS o
                   JOIN customers AS c ON c.id = o.customer_id
                   WHERE c.city = 'Faro');
  1. Which cities have customers who have placed a paid order? Write it with IN and a subquery, and each city only once.
Answer

Lisbon (Ada), Porto (Ben) and Braga (Dara). IN does not repeat a customer who has several matching orders, but two customers of one city would both be kept, so DISTINCT is still needed for “each city once”, even though no city here has two such customers:

SELECT DISTINCT city
FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE status = 'paid')
ORDER BY city;
  1. Without running them, how many rows do SELECT city FROM customers UNION ALL SELECT city FROM shipping_zones and the same with EXCEPT ALL swapped sides (zones first) return?
Answer

9 and 1. UNION ALL keeps all six customer rows and all three zone rows. With the zones first, EXCEPT ALL takes Lisbon, Porto and Faro (one copy each) and subtracts the customers’ cities: Lisbon and Porto have copies to cancel them, Faro does not.

SELECT count(*) AS union_all
FROM (SELECT city FROM customers UNION ALL SELECT city FROM shipping_zones) AS u;
SELECT city FROM shipping_zones
EXCEPT ALL
SELECT city FROM customers;
  1. Find the customers who have orders in every status that occurs in the table (paid, shipped and cancelled).
Answer

“No status is missing for this customer” is a NOT EXISTS around an EXCEPT: the statuses that occur, minus this customer’s statuses, must be empty. Only Ada has all three:

SELECT c.name
FROM customers AS c
WHERE NOT EXISTS (SELECT status FROM orders
                  EXCEPT
                  SELECT status FROM orders AS o WHERE o.customer_id = c.id)
ORDER BY c.id;

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 draftcount(*) against count(x), FILTER, ordered string_agg and array_agg, any_value, and grouping by a primary key.
  • 06 Subqueries and set operations draftScalar, IN, EXISTS, ANY and ALL subqueries, correlated subqueries, and UNION, INTERSECT and EXCEPT with and without ALL.
  • 07 Sorting and paging draftNULLS 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.