HashAggregate Versus GroupAggregate Plan Choice

Compare the two aggregation paths with EXPLAIN: hash builds first, group aggregates over sorted input, and enable_hashagg flips the plan for comparison.

SqlData Integrity

Code

snippet
-- the same GROUP BY has two physical paths:
--   HashAggregate: builds a hash table first, no input sort needed; faster when groups are few and memory suffices
--   GroupAggregate: sorts by the group key first, then scans and aggregates; the output comes out ordered
CREATE TEMP TABLE readings (
    sensor text    NOT NULL,
    value  numeric NOT NULL
);

INSERT INTO readings (sensor, value) VALUES
    ('a1', 20), ('b2', 21), ('a1', 22), ('b2', 23), ('a1', 24);

-- no ORDER BY: watch which path EXPLAIN picks for the aggregate node
EXPLAIN (COSTS OFF)
SELECT sensor, count(*), avg(value) FROM readings GROUP BY sensor;

-- when output must be ordered by the group key, GroupAggregate over sorted input skips an extra Sort node and usually wins
EXPLAIN (COSTS OFF)
SELECT sensor, count(*) FROM readings GROUP BY sensor ORDER BY sensor;

-- controlled experiment: turn off HashAggregate to force GroupAggregate, then look at the first query's plan again
SET enable_hashagg = off;
EXPLAIN (COSTS OFF)
SELECT sensor, count(*), avg(value) FROM readings GROUP BY sensor;
RESET enable_hashagg;

Inside the snippet

Several statements share this file — SELECT / INSERT / CREATE / EXPLAIN, with readings among the objects involved.

readings is created in this same file as session-local temp tables — nothing needs to exist beforehand, and it goes away at session end.

What the statements actually assemble: COUNT, AVG aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.

Putting it to use

The file is self-contained: it creates the session-local tables it uses (readings), so run it as a whole against a scratch database.

Core lines

EXPLAIN (COSTS OFF)
SELECT sensor, count(*) FROM readings GROUP BY sensor ORDER BY sensor;
EXPLAIN (COSTS OFF)
SELECT sensor, count(*), avg(value) FROM readings GROUP BY sensor;
INSERT INTO readings (sensor, value) VALUES
('a1', 20), ('b2', 21), ('a1', 22), ('b2', 23), ('a1', 24);

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
The references are `readings`.