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.
Code
-- 排序内存装不下时,排序节点把数据落盘做外部归并,
-- 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.
FAQ
- Name the tables involved in this file.
- `measurements`, `generate_series` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.