CTEs vs. Temporary Tables in SQL: When Readability Matters and When You Need Materialization and IndexesBrief · digest for November 28
Brief≈ 2 min

CTEs vs. Temporary Tables in SQL: When Readability Matters and When You Need Materialization and Indexes

Long SQL queries are easier to read when split into steps with WITH (CTEs) or a temporary table. They look similar on paper, yet the database planner treats them very differently.

A CTE lives for a single query and cannot have indexes. In PostgreSQL 12+, a single-use CTE is inlined into the plan so WHERE filters push inside. Repeated CTEs materialize automatically, and you can override that behavior with AS MATERIALIZED or AS NOT MATERIALIZED.

A temporary table (CREATE TEMP TABLE or SELECT ... INTO #Table in SQL Server) keeps rows for the whole session or until commit (ON COMMIT DROP), gathers planner statistics, and supports CREATE INDEX.

-- CTE: readable one-off step
WITH dept_counts AS (
  SELECT department, COUNT(employee_id) AS total
  FROM employees GROUP BY department
)
SELECT department, total FROM dept_counts WHERE total > 5;

-- Temporary table with an index (PostgreSQL)
CREATE TEMP TABLE dept_counts AS
SELECT department, COUNT(employee_id) AS total
FROM employees GROUP BY department;
CREATE INDEX ON dept_counts (total);
SELECT department, total FROM dept_counts WHERE total > 5;

If you pass millions of rows through several JOINs, an indexed temp table can make reports multiples faster. On a read-only replica without write access, though, it won't work, and frequent recreation under load bloats pg_class and pg_attribute. For one-off queries, stick with a CTE.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 3