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.

SqlData Fetching

Code

snippet
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

FAQ

What relations does the SQL touch?
`regions`, `orders`, `generate_series` — joined via one JOIN clause.