man postgres/aggregates
lesson 5 of 34 · Querying
Aggregates and GROUP BY
How many orders came in during April, and for how much?
SELECT count(*) AS orders, sum(total) AS revenue
FROM orders
WHERE ordered_on >= '2026-04-01'; orders | revenue
--------+---------
0 |
(1 row)None: every order in the table is from March. One row says so, with a count of 0 and a sum that is NULL. Now the same question per customer:
SELECT customer_id, count(*) AS orders, sum(total) AS revenue
FROM orders
WHERE ordered_on >= '2026-04-01'
GROUP BY customer_id;customer_id | orders | revenue -------------+--------+--------- (0 rows)
Not five rows of zeros: no rows at all. Both answers are right, and the difference is the first thing to understand about aggregates. Without GROUP BY, an aggregate query puts all its input rows into a single group, and that group exists even when the input is empty, so the query returns exactly one row (unless a HAVING clause removes it). With GROUP BY, a group is made for each distinct value (or combination of values) of the GROUP BY expressions that occurs in the input. No rows, no values, no groups.
To get a row per customer with 0 in it, the customers have to come from
somewhere other than the orders: start from customers, LEFT JOIN the April
orders (the condition goes in ON, as the lesson on joins showed), and count
a column that is NULL on the rows the join added:
SELECT c.name, count(o.id) AS orders, coalesce(sum(o.total), 0) AS revenue
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id AND o.ordered_on >= '2026-04-01'
GROUP BY c.id
ORDER BY c.id;name | orders | revenue -------+--------+--------- Ada | 0 | 0 Ben | 0 | 0 Chen | 0 | 0 Dara | 0 | 0 Eli | 0 | 0 Farah | 0 | 0 (6 rows)
This lesson goes through what a group is, what each common aggregate does with its rows, NULLs included, and the parts of the syntax that are easy to get wrong: DISTINCT, FILTER, ORDER BY inside an aggregate, and the rule for which columns SELECT may use.
The data
The customers and orders of the lessons on NULL and joins, unchanged, plus the four beans the roaster sells and the lines of each order: which beans, and how many 250 g bags of each. The data is in the setup script.
CREATE TABLE products (
id integer PRIMARY KEY,
name text NOT NULL UNIQUE,
origin text NOT NULL,
price numeric(6,2) NOT NULL
);
CREATE TABLE order_lines (
order_id integer NOT NULL REFERENCES orders,
product_id integer NOT NULL REFERENCES products,
bags integer NOT NULL CHECK (bags > 0),
PRIMARY KEY (order_id, product_id)
);
SELECT * FROM products ORDER BY id;id | name | origin | price ----+-------------+----------+------- 1 | Yirgacheffe | Ethiopia | 14.50 2 | Huila | Colombia | 12.00 3 | Santos | Brazil | 9.75 4 | Kiambu | Kenya | 16.25 (4 rows)
SELECT id, customer_id, status, total, rating FROM orders ORDER BY id;id | customer_id | status | total | rating -----+-------------+-----------+-------+-------- 101 | 1 | shipped | 42.00 | 5 102 | 2 | shipped | 18.50 | 103 | 1 | cancelled | 60.00 | 104 | 3 | shipped | 75.25 | 4 105 | 2 | paid | 31.00 | 106 | 4 | cancelled | 12.00 | 107 | 1 | paid | 27.50 | 108 | 5 | shipped | 99.90 | 2 109 | 3 | shipped | 23.75 | 110 | 4 | paid | 64.00 | 111 | 2 | shipped | 42.00 | 5 112 | 5 | cancelled | 15.00 | (12 rows)
The twelve orders have twenty lines between them. Every box on this page gives the same output live as recorded.
A group keeps a state for each aggregate
GROUP BY puts the rows that WHERE kept into piles, one per distinct value of the grouping expressions. Each aggregate in the query then keeps a small state per pile: a count, a running sum, the largest value so far. Each row that arrives updates the states of its own group, and at the end each group turns into one output row. This query has three aggregates, one of them with a FILTER, which is explained further down:
SELECT customer_id,
count(*) AS orders,
count(rating) AS rated,
sum(total) FILTER (WHERE status <> 'cancelled') AS spent
FROM orders
GROUP BY customer_id
ORDER BY customer_id; customer_id | orders | rated | spent
-------------+--------+-------+-------
1 | 3 | 1 | 69.50
2 | 3 | 1 | 91.50
3 | 2 | 1 | 99.00
4 | 2 | 0 | 64.00
5 | 2 | 1 | 99.90
(5 rows)Step through the rows as they fall into their groups:
The 12 orders are taken in id order and each is added to the group of its customer. count(*) goes up by one for every row; count(rating) only for rows with a rating; spent only for rows that are not cancelled. Customer 4's spent is NULL after its first order, which is cancelled, and becomes 64.00 with the second. The five final states are the five rows of the GROUP BY query. (This figure steps through a recorded run; it needs JavaScript.)
The state after each row is the same aggregates computed as window
functions over the rows of the group so far, run against PostgreSQL 19.0
by the lesson’s trace.py, and the final states are checked against the
real GROUP BY query. This is what grouping means, not how the executor
works: it may sort the rows or hash them, and it reads them in no
particular order.
Three things show in the figure. count(*) goes up for every row.
count(rating) and sum(total) skip a row whose input is NULL or, for
spent, a row the FILTER leaves out. And a state that has seen no input yet
is the aggregate’s answer for “no rows”: 0 for the counts, NULL for the sum,
which is why customer 4’s spent is NULL after its first order, a
cancelled one. Customer 6, Farah, has no orders, so she never gets a group.
count(*), count(x) and count(DISTINCT x)
The lesson on NULL showed the first two: count(*) counts rows, and
count(x) counts the rows where x is not NULL. The third, count(DISTINCT x), counts the different non-NULL values of x. Over the lines of each
customer’s orders, it tells lines from beans:
SELECT c.name,
count(*) AS lines,
count(DISTINCT l.product_id) AS beans,
sum(l.bags) AS bags
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
JOIN order_lines AS l ON l.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY c.id
ORDER BY c.id;name | lines | beans | bags ------+-------+-------+------ Ada | 4 | 3 | 5 Ben | 5 | 3 | 6 Chen | 3 | 2 | 6 Dara | 2 | 2 | 4 Eli | 2 | 2 | 6 (5 rows)
Ben has five lines over his three orders, but only three different beans.
DISTINCT works inside the ordinary aggregates, sum and string_agg as
much as count, and it is about values, not rows. That
is a trap when it is used to undo a join that multiplied rows. Here is the
revenue of the shipped orders, computed over a join with their lines:
SELECT sum(o.total) AS revenue,
sum(DISTINCT o.total) AS distinct_totals,
count(*) AS rows,
count(DISTINCT o.id) AS orders
FROM orders AS o
JOIN order_lines AS l ON l.order_id = o.id
WHERE o.status = 'shipped';revenue | distinct_totals | rows | orders ---------+-----------------+------+-------- 560.55 | 259.40 | 10 | 6 (1 row)
Six shipped orders on ten rows. sum(o.total) adds each order once per line
and gives 560.55. sum(DISTINCT o.total) looks like the fix, but it adds
each different amount once, and orders 101 and 111 both total 42.00, so
one of them is lost: 259.40. The right answer is the sum over orders
alone:
SELECT sum(total) AS revenue
FROM orders
WHERE status = 'shipped';revenue --------- 301.40 (1 row)
count(DISTINCT o.id) is safe because the id is unique per order; a sum or
average over a fanned-out join is not, and the fix is the one from the
lesson on joins: aggregate each table before joining.
NULL inputs and empty groups
“Aggregates skip NULLs” is true of count(x), sum, avg, min, max
and most others, but not of all of them. array_agg and json_agg collect
every input, NULL included. string_agg skips NULLs, and json_agg_strict
is the variant of json_agg that does. Ada has three orders, one of them
rated:
SELECT array_agg(rating ORDER BY id) AS array_agg,
string_agg(rating::text, ',' ORDER BY id) AS string_agg,
json_agg(rating ORDER BY id) AS json_agg,
json_agg_strict(rating ORDER BY id) AS json_agg_strict
FROM orders
WHERE customer_id = 1; array_agg | string_agg | json_agg | json_agg_strict
---------------+------------+-----------------+-----------------
{5,NULL,NULL} | 5 | [5, null, null] | [5]
(1 row)For a list of values, add FILTER (WHERE x IS NOT NULL) to array_agg when
the NULLs are not wanted.
The other half is what an aggregate returns when it gets no input at all:
there are no rows or, for an aggregate that skips NULLs, all its inputs
were NULL. The counts say 0. Most other aggregates say NULL: there is
nothing to add up, compare or collect, so array_agg of no rows gives
NULL, not an empty array.
SELECT count(*) AS count, regr_count(total, rating) AS regr_count,
sum(total) AS sum, max(total) AS max,
array_agg(id) AS array_agg, bool_and(true) AS bool_and
FROM orders
WHERE ordered_on >= '2026-04-01'; count | regr_count | sum | max | array_agg | bool_and
-------+------------+-----+-----+-----------+----------
0 | 0 | | | |
(1 row)regr_count, one of the statistics aggregates, is a count too, of the rows
where both of its inputs are non-NULL. Wrap the others in coalesce when the
reader expects 0 or '{}'.
FILTER
Often one query needs several aggregates over different subsets of the same rows: how many orders each customer cancelled, and how much they spent on the rest. A WHERE clause can’t do that, because it removes rows for every aggregate at once. A FILTER clause after an aggregate decides which rows that one aggregate sees:
SELECT customer_id,
count(*) AS orders,
count(*) FILTER (WHERE status = 'cancelled') AS cancelled,
sum(total) FILTER (WHERE status <> 'cancelled') AS spent,
sum(total) FILTER (WHERE status = 'paid') AS unshipped
FROM orders
GROUP BY customer_id
ORDER BY customer_id; customer_id | orders | cancelled | spent | unshipped
-------------+--------+-----------+-------+-----------
1 | 3 | 1 | 69.50 | 27.50
2 | 3 | 0 | 91.50 | 31.00
3 | 2 | 0 | 99.00 |
4 | 2 | 1 | 64.00 | 64.00
5 | 2 | 1 | 99.90 |
(5 rows)A row goes into the aggregate when the FILTER condition is true; false and
NULL both leave it out, as in WHERE. Customers 3 and 5, Chen and Eli, have no
paid order, so their unshipped is NULL: the sum saw no rows. Moving status = 'paid' into
WHERE would answer a different question. Their groups would have no rows,
and they would vanish from the result:
SELECT customer_id, count(*) AS orders, sum(total) AS unshipped
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
ORDER BY customer_id; customer_id | orders | unshipped
-------------+--------+-----------
1 | 1 | 27.50
2 | 1 | 31.00
4 | 1 | 64.00
(3 rows)The same can be written without FILTER, with a CASE inside the aggregate that yields NULL for the rows to leave out. That works for the aggregates that skip NULLs, and only for them:
SELECT customer_id,
count(CASE WHEN status = 'cancelled' THEN 1 END) AS cancelled,
sum(CASE WHEN status = 'paid' THEN total END) AS unshipped,
array_agg(id ORDER BY id) FILTER (WHERE status = 'paid') AS paid_filter,
array_agg(CASE WHEN status = 'paid' THEN id END ORDER BY id) AS paid_case
FROM orders
GROUP BY customer_id
ORDER BY customer_id; customer_id | cancelled | unshipped | paid_filter | paid_case
-------------+-----------+-----------+-------------+-----------------
1 | 1 | 27.50 | {107} | {NULL,NULL,107}
2 | 0 | 31.00 | {105} | {NULL,105,NULL}
3 | 0 | | | {NULL,NULL}
4 | 1 | 64.00 | {110} | {NULL,110}
5 | 1 | | | {NULL,NULL}
(5 rows)The counts and sums match the FILTER version. The two arrays don’t:
array_agg keeps NULLs, so the CASE version has a NULL for every order that
is not paid, and FILTER leaves those orders out. For Chen and Eli it leaves
nothing at all, and array_agg of no rows is NULL, as the section above
showed. FILTER also says what it
means, so it is the better habit.
Ordered aggregates: string_agg and array_agg
Most aggregates don’t care in which order their rows arrive: a sum is a
sum. string_agg, array_agg and the JSON aggregates do: their result
lists the inputs in the order they were fed in. Without an ORDER BY inside
the call, that order is whatever the plan produces, and it can change when
the plan does. With one, it is fixed. This lists the beans each customer has
ordered, each once, in alphabetical order, and the ids of their orders:
SELECT c.name,
string_agg(DISTINCT p.name, ', ' ORDER BY p.name) AS beans,
array_agg(DISTINCT o.id ORDER BY o.id) AS orders
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
JOIN order_lines AS l ON l.order_id = o.id
JOIN products AS p ON p.id = l.product_id
GROUP BY c.id
ORDER BY c.id; name | beans | orders
------+------------------------------------+---------------
Ada | Huila, Kiambu, Santos, Yirgacheffe | {101,103,107}
Ben | Huila, Santos, Yirgacheffe | {102,105,111}
Chen | Huila, Kiambu | {104,109}
Dara | Huila, Kiambu, Santos | {106,110}
Eli | Kiambu, Santos, Yirgacheffe | {108,112}
(5 rows)The ORDER BY goes after all the arguments. Placed after the first one, it
is still valid syntax, but it now means a single-argument aggregate with two
sort keys, and string_agg has no single-argument form:
SELECT string_agg(status ORDER BY id, ', ')
FROM orders;ERROR: function string_agg(text) does not exist
LINE 1: SELECT string_agg(status ORDER BY id, ', ')
^
DETAIL: No aggregate function matches the given name and argument types.
HINT: Perhaps you misplaced ORDER BY; ORDER BY must appear after all regular arguments of the aggregate.The HINT names the mistake. With DISTINCT, there is a second rule: the ORDER BY can only use the expressions being aggregated. DISTINCT keeps one copy of each value, and once two rows with the same status are one, that value has no single id to sort by:
SELECT array_agg(DISTINCT status ORDER BY id)
FROM orders;ERROR: in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list
LINE 1: SELECT array_agg(DISTINCT status ORDER BY id)
^An older habit is to sort the rows in a subquery and aggregate them in the outer query without an ORDER BY. That usually works, but nothing guarantees it: if the outer query does more, such as joining another table, the rows may reach the aggregate in a different order. Put the ORDER BY in the call.
bool_and and bool_or
Two aggregates answer yes-or-no questions about a group. bool_and(c) is
true if c was true for every row of the group, and bool_or(c) if it was
true for at least one. every is the SQL standard’s name for bool_and.
Both skip NULLs like the other aggregates:
SELECT customer_id,
bool_and(status <> 'cancelled') AS never_cancelled,
bool_or(rating = 5) AS gave_a_five,
every(shipped_on IS NOT NULL) AS all_shipped
FROM orders
GROUP BY customer_id
ORDER BY customer_id; customer_id | never_cancelled | gave_a_five | all_shipped
-------------+-----------------+-------------+-------------
1 | f | t | f
2 | t | t | f
3 | t | f | t
4 | f | | f
5 | f | f | f
(5 rows)Customer 4, Dara, rated nothing, so rating = 5 is NULL on both of her
rows, bool_or sees no input and returns NULL, not false. The condition
shipped_on IS NOT NULL is never NULL, so all_shipped is always true or
false. The same yes-or-no questions can also be asked with FILTER, as in
count(*) FILTER (WHERE status = 'cancelled') = 0, which gives false or
true and never NULL.
Which columns SELECT may use
After GROUP BY, a row of the result stands for a group. SELECT, HAVING and
ORDER BY may use the grouping expressions, aggregates, and constants. A
column that is neither has many values in a group, and PostgreSQL refuses
to pick one. The first lesson showed the exception: when a query groups by a
table’s primary key, the other columns of that table are allowed too,
since the key determines them. The rule is narrow, and it is easy to step
outside it. Grouping by o.customer_id is not grouping by c.id, even
though the join makes the two equal on every row:
SELECT o.customer_id, c.name, count(*) AS orders
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
GROUP BY o.customer_id;ERROR: column "c.name" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT o.customer_id, c.name, count(*) AS orders
^And only the primary key counts. A UNIQUE column, even a NOT NULL one, also
determines the rest of the row, but this rule does not take it into
account.
products.name is UNIQUE and NOT NULL:
SELECT p.name, p.origin, sum(l.bags) AS bags
FROM order_lines AS l
JOIN products AS p ON p.id = l.product_id
GROUP BY p.name;ERROR: column "p.origin" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT p.name, p.origin, sum(l.bags) AS bags
^There are four ways out. Group by the primary key (GROUP BY p.id), and
the other columns of products are allowed. List the extra columns in GROUP
BY as well, which changes nothing when they are determined by the key.
Wrap the column in min() or max(), which pick a definite value. Or use
any_value, which returns some non-NULL value from the group without
saying which:
SELECT p.name, any_value(p.origin) AS origin, sum(l.bags) AS bags
FROM order_lines AS l
JOIN products AS p ON p.id = l.product_id
GROUP BY p.name
ORDER BY p.name;name | origin | bags -------------+----------+------ Huila | Colombia | 10 Kiambu | Kenya | 9 Santos | Brazil | 5 Yirgacheffe | Ethiopia | 9 (4 rows)
any_value is the honest choice when you know every row of the group has
the same value, as here, and want to say so. It is the wrong choice when
the values differ and you care which one you get: grouped by city,
any_value(name) returns one customer’s name per city, and nothing defines
whose.
Aggregates of aggregates
An aggregate’s argument can’t contain another aggregate. “The largest number of orders any customer placed” is a maximum of per-customer counts, and the direct way to write it fails:
SELECT max(count(*))
FROM orders
GROUP BY customer_id;ERROR: aggregate function calls cannot be nested
LINE 1: SELECT max(count(*))
^Group in a subquery, and aggregate its rows in the outer query:
SELECT max(orders) AS most_orders, avg(orders) AS avg_orders
FROM (SELECT customer_id, count(*) AS orders
FROM orders
GROUP BY customer_id) AS per_customer; most_orders | avg_orders
-------------+--------------------
3 | 2.4000000000000000
(1 row)The other way to combine two levels is a window function over the groups,
as in the first lesson’s sum(sum(total)) OVER (): that is allowed, because
the window function runs after the grouping.
Medians and modes: WITHIN GROUP
avg is easily pulled by one large value. The median, the middle value
once the inputs are sorted, is not, and it needs the inputs in order. Such
aggregates are called ordered-set aggregates, and their sort order is
written in a WITHIN GROUP (ORDER BY ...) clause after the call:
SELECT avg(total) AS mean,
percentile_cont(0.5) WITHIN GROUP (ORDER BY total) AS median,
percentile_disc(0.5) WITHIN GROUP (ORDER BY total) AS median_disc,
mode() WITHIN GROUP (ORDER BY total) AS mode
FROM orders;mean | median | median_disc | mode ---------------------+--------+-------------+------- 42.5750000000000000 | 36.5 | 31.00 | 42.00 (1 row)
The twelve totals, sorted, have 31.00 and 42.00 in the middle, as the sixth
and seventh. percentile_cont(0.5) interpolates between them and returns
36.5, a double precision value that need not be one of the inputs.
percentile_disc(0.5) returns an actual input, the first one at or past
the halfway point: 31.00. mode() returns the most frequent value, 42.00,
which appears twice. The 0.5 is a fraction between 0 and 1, so
percentile_cont(0.9) is the 90th percentile.
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.
- For each product, show how many bags were ordered in orders that were not cancelled, and in how many different orders. Every product should appear.
Answer
Group by the product’s primary key, so that p.name is allowed. All four
products have lines in orders that were not cancelled, so a plain join
loses none of them:
SELECT p.name, sum(l.bags) AS bags, count(DISTINCT l.order_id) AS orders
FROM products AS p
JOIN order_lines AS l ON l.product_id = p.id
JOIN orders AS o ON o.id = l.order_id
WHERE o.status <> 'cancelled'
GROUP BY p.id
ORDER BY p.id;
Huila leads with 10 bags over 6 orders. count(DISTINCT l.order_id) is
the same as count(*) here, since the primary key of order_lines allows
one line per product per order.
- In one row: the number of orders, the number of shipped orders, and the share of shipped orders that got a rating, as a percentage.
Answer
Three FILTERs over the same rows:
SELECT count(*) AS orders,
count(*) FILTER (WHERE status = 'shipped') AS shipped,
round(100.0 * count(rating) FILTER (WHERE status = 'shipped')
/ count(*) FILTER (WHERE status = 'shipped'), 1) AS pct_rated
FROM orders;
12 orders, 6 shipped, 4 of them rated: 66.7.
- For each city that has customers, list the customer names in
alphabetical order, separated by
" / ", and the number of customers.
Answer
SELECT city, string_agg(name, ' / ' ORDER BY name) AS customers, count(*) AS n
FROM customers
GROUP BY city
ORDER BY city;
- Predict the result, then check:
SELECT count(*), count(email), count(DISTINCT email), count(DISTINCT city) FROM customers;
Answer
6, 4, 4 and 4. Two customers have no email, and the four emails are all different; the six customers live in four cities.
SELECT count(*), count(email), count(DISTINCT email), count(DISTINCT city)
FROM customers;
- Which customers have placed more than one order, and all of them not cancelled? Use one aggregate in HAVING for each condition.
Answer
Ben and Chen. Ada, Dara and Eli each have a cancelled order; Farah has none at all, and has no group:
SELECT c.name
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id
HAVING count(*) > 1 AND bool_and(o.status <> 'cancelled')
ORDER BY c.id;
Sources
The PostgreSQL 19 documentation:
- Aggregate expressions: the syntax of an aggregate call, DISTINCT, ORDER BY inside the call, FILTER and WITHIN GROUP, and which aggregates ignore NULL inputs.
- Aggregate functions: every built-in aggregate, which ones include NULLs, what they return for no rows, why a sorted subquery is not a reliable way to order their input, and the ordered-set aggregates.
- Table expressions: GROUP BY and HAVING, and grouping by a primary key.
- SELECT: the GROUP BY clause and functional dependency.
- Aggregate functions in the tutorial.
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.