Memoize Node Caches Repeated Lookups
A nested-loop join whose outer keys repeat earns a Memoize node: parameterized inner scans skip work on cache hits, reported in EXPLAIN ANALYZE.
Code
CREATE TABLE orders (
id int PRIMARY KEY,
region_id int NOT NULL
);
CREATE TABLE regions (
id int PRIMARY KEY,
name text NOT NULL
);
-- 10000 单只来自 4 个 region:外层键高度重复,正是 Memoize 的适用面
INSERT INTO regions VALUES (1,'eu'),(2,'us'),(3,'ap'),(4,'sa');
INSERT INTO orders
SELECT g, (g % 4) + 1 FROM generate_series(1, 10000) g;
-- PG 14+:enable_memoize 默认开启;压住 hash/merge join,强制 nested loop
-- 走内层参数化索引扫描
SET enable_hashjoin = off;
SET enable_mergejoin = off;
EXPLAIN (ANALYZE, COSTS OFF)
SELECT o.id, r.name
FROM orders o
JOIN regions r ON r.id = o.region_id;
RESET enable_hashjoin;
RESET enable_mergejoin;How the snippet works
SELECT / INSERT / CREATE / EXPLAIN statements share the script, touching regions, orders and generate_series.
Breaking the statements into their working parts: one JOIN combining rows across tables; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
The regions table is the working surface here.
Statements that matter
EXPLAIN (ANALYZE, COSTS OFF)
SELECT o.id, r.name
FROM orders o
JOIN regions r ON r.id = o.region_id;
INSERT INTO orders
SELECT g, (g % 4) + 1 FROM generate_series(1, 10000) g;
CREATE TABLE orders (
id int PRIMARY KEY,
region_id int NOT NULL
);
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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What relations does the SQL touch?
- `regions`, `orders`, `generate_series` — joined via one JOIN clause.
Report a problem with this exampleOpens a pre-filled issue on GitHub.