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.

SqlData Integrity

Code

snippet
-- 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

FAQ

Which tables or CTEs does it reference?
The references are `generate_series`, `src`, `picks`.