Problem Statement
When does a temporary table often outperform a large CTE?
Explanation
Many optimizers inline CTEs, so heavy subqueries can be recomputed. Persisting the step to a temp table lets you index it, reuse it, and control row counts.
This can lower total work and give the optimizer better cardinality for later joins.
Code Solution
SolutionRead Only
CREATE TEMP TABLE recent AS SELECT * FROM events WHERE ts>=NOW()-INTERVAL '7 days'; CREATE INDEX ON recent(user_id); SELECT ... FROM recent r JOIN users u ON u.id=r.user_id;
