Sub topic 7
Sorts, aggregates and limits
This chapter assumes you can read a plan as a tree, know that each node shows cost=startup..total, and have run EXPLAIN ANALYZE before. It covers the nodes that usually sit at the top of a plan: Sort, the aggregate family, and Limit. Their behavior explains many slow queries and many plans that look wrong but are fine.
Sort nodes
A Sort node reads all of its input rows, orders them, and then returns them. The planner adds one for ORDER BY, for a merge join whose inputs are not already ordered, for GroupAggregate, and for some DISTINCT and window queries.
Sort is a blocking node. It cannot return its first row until it has consumed every input row. Its startup cost is therefore close to its total cost, and it is roughly the child's total cost plus the cost of the comparisons.
EXPLAIN ANALYZE reports how the sort ran:
Sort (cost=5321.40..5334.90 rows=5400 width=40) (actual time=48.201..48.203 rows=10 loops=1)
Sort Key: (count(*)) DESC
Sort Method: top-N heapsort Memory: 26kB| Sort Method | Meaning |
|---|---|
| `quicksort Memory: ...` | The whole input fit in `work_mem` and was sorted in memory. |
| `top-N heapsort Memory: ...` | A `LIMIT` sits above the sort, so PostgreSQL keeps only the best N rows. |
| `external merge Disk: ...` | The input did not fit in `work_mem`. PostgreSQL wrote temporary files and merged them. |
An external merge line is the main thing to look for. The sort then does temporary-file I/O, and the node is often slow. You can fix it in three ways:
- Raise
work_memfor the session or transaction. - Reduce the number of rows or columns that reach the sort.
- Provide the order from an index so no sort is needed.
BEGIN;
SET LOCAL work_mem = '64MB';
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders ORDER BY created_at;
ROLLBACK;Index order and incremental sort
If an index already delivers rows in the requested order, the Sort node disappears:
CREATE INDEX orders_created_at_idx ON orders (created_at);
EXPLAIN
SELECT * FROM orders ORDER BY created_at LIMIT 10;Limit (cost=0.43..0.89 rows=10 width=64)
-> Index Scan using orders_created_at_idx on orders (cost=0.43..45210.43 rows=980000 width=64)PostgreSQL 13 and later can also use Incremental Sort. If the input is already sorted by a and you ask for ORDER BY a, b, the node sorts one group of equal a values at a time. The plan shows Presorted Key: a. This needs far less memory than a full sort, and it can return rows early.
Aggregate nodes
Aggregation turns many rows into fewer rows. PostgreSQL has three main strategies, and the node name tells you which one it chose.
| Node | Input requirement | How it works | Typical use |
|---|---|---|---|
| `Aggregate` | None | One output row for the whole input, such as `SELECT count(*) FROM orders` | No `GROUP BY` |
| `HashAggregate` | None | Builds a hash table with one entry per group | Many unsorted rows, groups fit in memory |
| `GroupAggregate` | Input sorted by the group key | Walks sorted rows and closes a group when the key changes | Input already ordered, or a sort is needed anyway |
HashAggregate is blocking. It emits no rows until it has read all input. GroupAggregate can stream. It returns each group as soon as that group ends, so it works well under a LIMIT when an index supplies the order.
The planner chooses between them by cost. If the hash table is estimated to fit in work_mem, hashing usually wins because it avoids a sort. If the input is already sorted, GroupAggregate is cheaper. A GROUP BY followed by an ORDER BY on the same key often yields GroupAggregate because one sort serves both.
In PostgreSQL 13 and later, a hash aggregate that outgrows work_mem spills to disk instead of failing. EXPLAIN ANALYZE shows this:
HashAggregate (cost=5124.00..5178.00 rows=5400 width=40) (actual time=45.1..46.9 rows=5312 loops=1)
Group Key: c.name
Batches: 1 Memory Usage: 913kBBatches: 1 means everything fit in memory. A larger number, together with Disk Usage, means the aggregate spilled. If the row estimate for the number of groups was far too low, the planner may have chosen hashing for a result that does not fit.
Parallel plans split aggregation in two. Each worker produces Partial HashAggregate or Partial Aggregate rows under a Gather node. A Finalize node above it combines them. This is normal and not a sign of duplicated work.
SELECT DISTINCT and UNION use similar machinery. You see either a HashAggregate on all output columns, or a Sort followed by Unique.
Limit nodes and early stopping
Limit stops pulling rows once it has the count it needs. PostgreSQL executes a plan by letting each node ask its child for the next row. A Limit therefore stops its children early, if they can produce rows incrementally.
The planner uses this when it costs a plan under a limit. It assumes the child produces rows at a steady rate and charges only the fraction needed. The Limit node's total cost is its startup cost plus a share of the child's run cost. In the index example above, the child's total cost is 45210, but the Limit's total is only 0.89, because it reads about 10 rows out of 980000.
This produces two common surprises.
- Plans change with the limit.
ORDER BY created_at LIMIT 10may use an index scan, whileLIMIT 500000on the same query uses a sort over a sequential scan. The costs differ because the fraction read differs. - Actual rows can be much lower than estimated rows without being a misestimate. A child under a Limit may show
rows=980000estimated androws=10actual, because it was stopped. Compare estimates only on nodes that ran to completion.
The planner can get this wrong. It assumes matching rows are spread evenly. Suppose you run WHERE status = 'open' ORDER BY id LIMIT 1, and the open rows are all at the end of the table. The index scan on id must then walk almost the whole index before it finds a match. The plan looks cheap and runs slowly.
A LIMIT without ORDER BY returns an arbitrary set of rows. The plan will happily stop early, but different runs can give different rows.
A full plan, read from the top
Here is the earlier report query, with a sample plan:
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.name, count(*) AS order_count
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.created_at >= DATE '2026-01-01'
GROUP BY c.name
ORDER BY order_count DESC
LIMIT 10;Limit (cost=5321.40..5321.43 rows=10 width=40) (actual time=48.201..48.203 rows=10 loops=1)
-> Sort (cost=5321.40..5334.90 rows=5400 width=40) (actual time=48.200..48.201 rows=10 loops=1)
Sort Key: (count(*)) DESC
Sort Method: top-N heapsort Memory: 26kB
-> HashAggregate (cost=5124.00..5178.00 rows=5400 width=40) (actual time=45.1..46.9 rows=5312 loops=1)
Group Key: c.name
Batches: 1 Memory Usage: 913kB
-> Hash Join (cost=310.00..4800.00 rows=64800 width=32) (actual time=3.1..35.0 rows=66021 loops=1)
...Read it from the inside out. The join produces 66021 rows. HashAggregate reduces them to 5312 groups. Sort orders the groups but keeps only 10 of them, which is why it says top-N heapsort. Limit returns those 10.
The sort is cheap here because the aggregate has already shrunk the input. The aggregate cost is dominated by its child, the join. When you hunt for a bottleneck, remember that actual time on a parent includes the time of its children. Subtract the child's time to find a node's own cost.
Common mistakes
- Treating a Sort as the problem when its input is the problem. Check
actual rowson the child first. - Raising
work_memglobally to fix one query. - Expecting
LIMITto make a query fast. If a blocking node such as Sort or HashAggregate sits below it, all input is still processed. - Reading low actual rows under a Limit as a bad estimate.
- Sorting by an expression that no index matches. An index on
created_atdoes not helpORDER BY date(created_at).
Exercise
A plan shows Sort Method: external merge Disk: 184320kB above a sequential scan, and the query has no LIMIT. Name two different ways to remove the disk spill, and say what you would check in the plan afterward.
Show answer
Raise work_mem for that query, for example with SET LOCAL work_mem = '256MB' inside a transaction. Or avoid the sort, either by creating an index that returns rows in the ORDER BY order or by reducing the rows and columns that reach the sort. Rerun EXPLAIN (ANALYZE, BUFFERS) and check that Sort Method now says quicksort Memory: ... or that the Sort node is gone.
Exercise
A query SELECT * FROM events ORDER BY id LIMIT 5 shows an Index Scan with rows=2000000 estimated and rows=5 actual. Is this a misestimate that needs fixing? Explain.
Show answer
No. The Limit node stopped the Index Scan after 5 rows, so the actual count is low on purpose. The estimate describes the full scan, which never ran to completion. Compare estimated and actual rows only on nodes that finished.