Sub topic 7
Sorts, aggregates and limits
Assume you can write SELECT queries with WHERE, JOIN, GROUP BY, and ORDER BY, and that you know an index can help find rows faster. This chapter uses PostgreSQL plan terminology.
Sort, aggregate, and limit nodes transform rows after scans and joins. Read them from the bottom up. A scan produces rows, an aggregate combines rows into groups, a sort orders rows, and a limit returns only part of the result.
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, count(*) AS order_count
FROM orders
WHERE created_at >= DATE '2026-01-01'
GROUP BY customer_id
ORDER BY order_count DESC
LIMIT 10;A simplified plan might look like this:
Sort nodes
A Sort node orders all rows it receives according to an ORDER BY clause. Its output can then be consumed by LIMIT, GroupAggregate, or another operation.
The plan reports the sort method. Common methods include:
quicksort: the rows fit in memory.top-N heapsort: PostgreSQL knows that only a small number of ordered rows are needed, often because ofLIMIT.external merge: the rows did not fit in memory, so PostgreSQL used temporary disk files.
A disk-based sort can be much slower than an in-memory sort. The relevant memory setting is usually work_mem, which applies to each sort or hash operation. Increasing it may help one query, but a high global value can use too much memory when many sessions run at once.
An index can sometimes provide rows in the required order. For example, an index on (created_at, customer_id) may help a query that filters and orders by compatible columns. PostgreSQL still chooses a sort when scanning the index would cost more than reading and sorting the table.
Aggregate nodes
An aggregate calculates one result from many input rows. count, sum, avg, min, and max are aggregate functions.
With GROUP BY, PostgreSQL commonly chooses one of these nodes:
| Node | Working model | Common requirement |
|---|---|---|
| `HashAggregate` | Builds a hash table for groups | Enough memory for the groups |
| `GroupAggregate` | Processes ordered input groups | Input already sorted or sorted first |
HashAggregate does not need its input to be ordered. It can be efficient when many rows form a manageable number of groups. If the hash table becomes too large, it may use temporary storage.
GroupAggregate reads one group at a time, so its input must be ordered by the grouping columns. An index or an earlier sort can provide that order. It is often useful when the query also needs ordered grouped output.
Limit nodes
A Limit node stops after it has received enough rows. It can reduce work, but it does not guarantee that earlier nodes process only that many rows.
For example, PostgreSQL may need to examine every qualifying row to find the ten rows with the greatest count. A LIMIT 10 after ORDER BY therefore does not make the aggregate or sort equivalent to processing ten rows.
LIMIT without ORDER BY is also nondeterministic. The database may return different rows after a plan change, vacuum operation, or data modification. Add an ordering that uniquely identifies the desired result.
Reading the combined operation
Inspect the actual rows, actual time, and sort method for each node. A large input to an aggregate may point to a weak filter. A large number of groups may make hashing expensive. A disk-based sort points to memory pressure or too many rows reaching the sort.
Exercise
Why can a query with ORDER BY total DESC LIMIT 10 still process thousands of rows?
Show answer
It must calculate and compare the qualifying rows before it can know which ten have the greatest totals.