TEMP Tables vs CTEs & the Fence in SQL
Named steps, reusable heavies, version-dependent fencing
CTE: readable named steps, multi-reference, recursive — one-statement scope. Subquery: single-use inline. TEMP table: multi-statement reuse, indexable, session-scoped — heavy pipelines and huge intermediates. PG <12 always materialized CTEs (optimization fence — no predicate pushdown); 12+ inlines by default (MATERIALIZED / NOT MATERIALIZED force either).
Subquery inline
Single-use FROM (SELECT…) — terser for trivial shapes, alias mandatory.
CTE named pipeline
WITH a AS (…), b AS (SELECT * FROM a …) — readable, multi-ref, recursive, testable per stage.
TEMP heavy reuse
Session-scoped, indexable, cross-statement — huge intermediates and multi-step jobs.
Fence is versioned
PG<12 fenced always; 12+ inlines. MATERIALIZED / NOT MATERIALIZED force either.
1-- PostgreSQL fence control:2WITH t AS MATERIALIZED (SELECT * FROM employees WHERE department = 'Engineering')3SELECT AVG(salary) FROM t;
| hint | effect |
|---|---|
| MATERIALIZED | compute-once fence |
| NOT MATERIALIZED | inline + pushdown |
Pre-12 fence could hurt (no pushdown) or help (shared scan). Knowing the version changes plan shapes — EXPLAIN reveals whether the CTE inlined or fenced.
Staged CTE pipeline
One idea per CTE, debuggable by stage.
1WITH base AS (SELECT * FROM employees WHERE age > 25),2enriched AS (SELECT * FROM base JOIN departments ON department = dept_id),3ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn FROM enriched)4SELECT * FROM ranked WHERE rn <= 2;
| shape | stages |
|---|---|
| staged | filter → enrich → rank → keep |
Fence control (PG)
Compute-once vs inline+pushdown.
1WITH t AS MATERIALIZED (SELECT * FROM employees WHERE department = 'Engineering')2SELECT AVG(salary) FROM t;
| hint | effect |
|---|---|
| MATERIALIZED | shared scan, no pushdown |
| NOT MATERIALIZED | inline, predicates push |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.