Sort Spill To Disk With Work Mem

Force sorts to spill to disk under a tiny work_mem, read the Sort Method line in EXPLAIN ANALYZE, and let an index on the sort key avoid the sort entirely.

SqlData Integrity

Code

snippet
-- 排序内存装不下时,排序节点把数据落盘做外部归并,
-- EXPLAIN ANALYZE 的 Sort Method 会如实显示
SET work_mem = '64kB';

CREATE TABLE measurements (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    sensor text NOT NULL,
    reading numeric NOT NULL
);

INSERT INTO measurements (sensor, reading)
SELECT 's' || g, random() * 100
FROM generate_series(1, 100000) AS g;

-- 无索引时全量排序:数据远超 work_mem,Sort Method 显示 external merge
EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF)
SELECT * FROM measurements ORDER BY reading;

-- 给排序列建索引:按索引顺序读即可满足 ORDER BY,排序节点消失
CREATE INDEX measurements_reading_idx ON measurements (reading);

EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF)
SELECT reading FROM measurements ORDER BY reading;

How it works

Setup and measurement alternate: CREATE/INSERT build measurements from generate_series, then SELECT/EXPLAIN observe where the sort spills.

In terms of clauses, the statements use: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Putting it to use

The measurements table is the working surface here.

Core lines

INSERT INTO measurements (sensor, reading)
SELECT 's' || g, random() * 100
FROM generate_series(1, 100000) AS g;
CREATE TABLE measurements (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sensor text NOT NULL,
reading numeric NOT NULL
);
EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF)
SELECT reading FROM measurements ORDER BY reading;

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
`measurements`, `generate_series` — referenced directly, no join needed.