← 中文资源

简体中文版本

HashAggregate 与 GroupAggregate 的计划取舍

同一条 GROUP BY 有两条物理路径:HashAggregate 免排序但耗内存,GroupAggregate 吃排序输入且输出天然有序;用 EXPLAIN 与 enable_hashagg 做对照实验。

阅读英文原文

实现说明

实际执行的是 SELECT / INSERT / CREATE / EXPLAIN——readings 是涉及的对象。 readings 是文件自己造的会话级临时表——库里不会有残留,会话终结即被清理。 把语句拆开看,工作部件是:用 COUNT、AVG 做聚合;GROUP BY 把同组行折叠成每个分组一行;ORDER BY 固定了输出顺序;必填列上的 NOT NULL 限定。

常见问题

这个脚本里出现了哪些表?

引用的是 readings。

核心语句

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);

代码示例

-- 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;