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.
Code
-- 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:
WHEREfirst, 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
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.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.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.
FAQ
- What are the relations in play here?
- `request_log`, `daily`, `hot`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.