Volatile CTE Evaluates Only Once
Volatile functions stop the planner from folding a CTE into the parent query, so two references to one random-valued CTE read the very same rows.
Code
-- volatile 函数让 planner 无法把 CTE 内联(fold)进主查询:
-- 带 random() 的 CTE 被物化,引用两次也只求值一次(evaluated only once),
-- 两个引用读到同一批行
-- 文档:SELECT containing no volatile functions can be folded into the parent query;
-- WITH queries are normally evaluated only once per execution of the parent
-- query, even if referred to more than once
WITH src AS (
SELECT g, random() AS r
FROM generate_series(1, 3) g
),
picks AS (
SELECT
(SELECT r FROM src WHERE g = 1) AS first_read,
(SELECT r FROM src WHERE g = 1) AS second_read
)
SELECT
first_read,
second_read,
first_read = second_read AS same_value -- 恒为 true:物化后只算一次
FROM picks;How the snippet works
What runs is SELECT, with generate_series, src and picks as the object involved.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause constraining which rows the statement operates on.
Using it
The generate_series table is the working surface here.
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
- Which tables or CTEs does it reference?
- The references are `generate_series`, `src`, `picks`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.