Learn SQL
-- subqueries.temp_vs_cte_fence

TEMP Tables vs CTEs & the Fence in SQL

Named steps, reusable heavies, version-dependent fencing

--concept

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).

--how it works
1

Subquery inline

Single-use FROM (SELECT…) — terser for trivial shapes, alias mandatory.

2

CTE named pipeline

WITH a AS (…), b AS (SELECT * FROM a …) — readable, multi-ref, recursive, testable per stage.

3

TEMP heavy reuse

Session-scoped, indexable, cross-statement — huge intermediates and multi-step jobs.

4

Fence is versioned

PG<12 fenced always; 12+ inlines. MATERIALIZED / NOT MATERIALIZED force either.

--visualization
WITH a AS (…), b AS (…) — named, multi-ref, recursive, testable
toolscope
CTEstatement, MATERIALIZED hint (PG12 pivot)
Stage 1 / 1
Trivial→subquery, structured→CTE, heavy/reused→TEMP. EXPLAIN reveals fence vs inline.
--example
query.sql
1-- PostgreSQL fence control:
2WITH t AS MATERIALIZED (SELECT * FROM employees WHERE department = 'Engineering')
3SELECT AVG(salary) FROM t;
Result
hinteffect
MATERIALIZEDcompute-once fence
NOT MATERIALIZEDinline + 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.

--variants

Staged CTE pipeline

One idea per CTE, debuggable by stage.

query.sql
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;
Result
shapestages
stagedfilter → enrich → rank → keep
1Each SELECT * FROM stage runs alone for debugging.
2Nesting four deep would be a maze.
3Filter-outside respects window evaluation order.

Fence control (PG)

Compute-once vs inline+pushdown.

query.sql
1WITH t AS MATERIALIZED (SELECT * FROM employees WHERE department = 'Engineering')
2SELECT AVG(salary) FROM t;
Result
hinteffect
MATERIALIZEDshared scan, no pushdown
NOT MATERIALIZEDinline, predicates push
1Materialized helps shared multi-ref scans.
2Inlined lets outer filters push into the CTE.
3EXPLAIN shows which happened.
--key facts
CTEnamed, statement-scoped, recursive
TEMPindexed, cross-statement, session scope
Fenceversion-dependent — PG12 pivot
--use cases
Monster-query refactors: nesting to stages
Heavy ETL steps: TEMP + indexes across statements
--under the hood
TEMP tables write WAL + need ANALYZE for stats; CTEs are optimization-transparent per hint.
Recursive CTEs only exist as WITH RECURSIVE — TEMP cannot recurse.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.