Sorting, grouping and memory boundaries

Trace an in-memory or external sort into grouping, then compare sort and hash aggregation without promising a universal fastest plan. Physical operators · Databases.

Sorting orders rows; grouping combines them. ORDER BY asks for order, while GROUP BY asks for group states. A sort can support either; a hash table can maintain groups.

When the input fits, and when it does not

Use events(event_id, team, amount) with rows e1/A/7, e2/B/3, e3/A/5 and e4/C/4, plus four work slots, each holding one row. These rows fit the stated premise, so the first frame can sort them in memory without a disk run. The scene names the capacity because a claim about spilling needs a capacity premise; a row count by itself does not prove that an engine will spill.

External sort into grouped output

Read the steps as text

  1. The initial frame has e1 through e4 and four work slots, each holding one row. Overflow rows e5 through e8 wait outside the first frame; the first run has not yet been written.
  2. Run 1 is written in output. The four work slots now hold e5, e6, e7 and e8 one row per slot; this overflow frame can be sorted into the next run.
  3. For SUM(amount) by team, the merged stream brings equal keys together. A is ready; B and C await emission. Sort preserves rows; grouping reduces them. Hash aggregation keeps group states and may spill.
  4. The run boundary explains temporary work; group emission explains logical reduction. No output-order promise exists until ORDER BY is requested.

At the run-boundary beat, introduce overflow rows e5/B/6, e6/A/2, e7/C/1 and e8/B/8. The initial frame contains e1 through e4; the second frame contains e5 through e8, so the complete eight-row input exceeds the four-slot premise. It reads a bounded chunk, sorts that chunk, and writes a sorted run to temporary storage. It repeats this for the remaining chunks. A merge pass then reads the heads of several runs, chooses the smallest next key, and writes a longer sorted run or the final ordered stream. The exact number of runs, merge fan-in and temporary pages depend on the engine and configuration. The stable idea is that external sort trades extra page movement for a bounded memory footprint.

Turning order into groups

For a separate, smaller illustration, suppose the sorted stream is A, A, B, B, B, C. A sort-based aggregate keeps the current key and its aggregate state. It consumes both A rows, emits the A result when B arrives, then starts B. For a simple sum, only the current group state is needed after the input is ordered; other aggregates can require more state. The logical GROUP BY may reduce many input rows to one output row per group, but it still counts every input row: if a prior join produced two rows for one order, COUNT(*) counts both; choosing a sort node cannot repair that upstream multiplicity mistake.

A hash aggregate takes another route. It hashes each group key to a table entry and updates that group's state as rows arrive. The input need not be ordered, but the hash table must retain one state per group (and any collision or transition state the engine requires). If the states exceed the allowed memory, an engine can partition or spill hash work and process partitions later. A spill is an implementation response to a resource boundary, not a different SQL meaning.

The two approaches also expose different useful properties. Sorted groups can feed a downstream merge or ordered output when the required keys line up. Hash aggregation can emit groups without first sorting all input, but its output order is not a promise. A planner may also choose a hybrid or parallel plan. Read a plan as evidence of the chosen implementation, not as a rule that one algorithm wins for every data shape.

Faded: a new report and a new boundary

In the faded scene, sales(store, day, order_id, amount) contains rows for North and South, and the request is GROUP BY store with no ORDER BY. State the premise before choosing: the sort path has two work slots, each holding one sales row, and the hash path has room for two group states. Decide what each path can emit and what it cannot prove about output order. If the scene adds ORDER BY store, the result-order requirement becomes explicit; if it adds a second aggregate such as COUNT(DISTINCT order_id), the declared row schema supplies that field while the physical node still supplies memory or run behavior.

Sort and hash under a small group budget

Read the steps as text

  1. For SUM(amount) by store, five sales rows form North=3 and South=2. The sort path has two work slots, each holding one sales row; the hash path has room for two group states, and the request has no ORDER BY.
  2. The row shape includes order_id for a possible distinct count. Sort can chunk five rows, while hash can retain the two group states under this teaching model; neither comparison proves a fastest plan.
  3. Adding ORDER BY store changes the logical request. The earlier result deliberately made no output-order promise.
  4. The faded comparison names row shape, group count and memory slots so the learner can qualify each path without inferring a universal winner.

The operator does not decide whether a group is semantically valid, whether NULL keys belong together, or whether a join duplicated rows. Those facts come from SQL semantics and the preceding relational lessons. It only receives an input stream and maintains the state needed to produce the requested aggregate. Statistics about row width, distinct groups, selectivity and available memory help a planner compare plans; stale estimates can make the chosen plan poor.

Recap

  • External sort makes bounded-memory runs and merges them; in-memory sort needs a fitting working set.
  • Sort aggregation emits adjacent groups, while hash aggregation retains per-group state and may spill when its budget is exceeded.
  • Sorting preserves input rows while grouping can reduce them according to the logical GROUP BY; neither physical choice repairs upstream multiplicity or creates result order without an explicit ORDER BY.
Why the memory premise belongs in the scene

The same query can use an in-memory sort, an external merge sort, a hash aggregate, or a parallel variant as data and configuration change. PostgreSQL 18 documents work_mem as a per-operation base for sorts and hash tables and hash_mem_multiplier as a separate multiplier for hash-based work; several operations and workers can consume memory at once. The lesson therefore uses small invented slots to make one local branch decidable and labels all spill and cost conclusions as engine- and configuration-qualified. See the version-pinned PostgreSQL 18 references in the private evidence receipt.

For a logical grouping refresher, practise grouping and HAVING in this track: that lesson owns which rows and groups the query means; this lesson owns how a physical operator can arrange and accumulate them.

Next Join algorithms: compare how nested loops, hash build and merge walks find matching pairs under their own input and memory premises.