CTE MATERIALIZED And NOT MATERIALIZED Hints

Force one-shot CTE evaluation with AS MATERIALIZED or allow inlining with AS NOT MATERIALIZED to control what the planner fuses into the outer query.

SqlData Fetching

Code

snippet
-- PostgreSQL 12+:无副作用且只被引用一次的 CTE 默认内联进外层查询;
-- AS MATERIALIZED 强制物化成一次求值的临时结果(优化栅栏),
-- 多次引用、易变表达式或需要固定评估时机时使用
WITH daily AS MATERIALIZED (
  SELECT occurred_at::date AS day,
         endpoint,
         COUNT(*)          AS calls,
         AVG(latency_ms)   AS avg_latency
  FROM request_log
  GROUP BY 1, 2
),
-- AS NOT MATERIALIZED:显式允许内联,外层过滤可以下推进来,单引用时通常更快
hot AS NOT MATERIALIZED (
  SELECT day, endpoint, calls, avg_latency
  FROM daily
  WHERE calls > 100
)
SELECT
  h.day,
  h.endpoint,
  h.calls,
  ROUND(h.calls * 100.0 / NULLIF(SUM(h.calls) OVER (PARTITION BY h.endpoint), 0), 2) AS share_pct
FROM hot h
ORDER BY h.day, h.endpoint;

How the snippet works

At its core this is a single SELECT statement against request_log, daily and hot.

In terms of clauses, the statements use: a WHERE clause narrowing which rows one statement affects; COUNT, SUM, AVG aggregation; a GROUP BY that collapses matching rows into one output row per group; a window function (OVER (…)) evaluating each row against its window peers while keeping every row in the output; an ORDER BY that fixes the output order.

Caveats

  • Remember the evaluation order: WHERE first, window functions later — filtering on the latter needs another query level.

Applying it

Run the statement against the request_log table.

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`request_log`, `daily`, `hot`.