SQL CTE Performance
Whether a CTE is a genuine optimization barrier depends on your Postgres version.
What & Why
Before Postgres 12, every CTE was an optimization fence — the planner always computed it fully in isolation, unable to push filters from the outer query into it. Since Postgres 12, a non-recursive CTE referenced only once is inlined by default — treated essentially like a subquery, with the planner free to optimize across the boundary.
See How It Works
BUSINESS QUESTION
Marketing filters recent converted leads once and summarizes them by source.
| id | campaign_id | created_at | qualified_at | converted_at | lead_score | source | country | |
|---|---|---|---|---|---|---|---|---|
| 301 | 1 | ana@example.com | 2024-01-21 09:10:00+00 | 2024-01-22 11:00:00+00 | 2024-02-02 10:00:00+00 | 86 | google_ads | US |
| 302 | 1 | ben@example.com | 2024-01-24 12:40:00+00 | NULL | NULL | 52 | google_ads | CA |
| 303 | 2 | chloe@example.com | 2024-02-16 08:30:00+00 | 2024-02-18 14:20:00+00 | NULL | 74 | GB | |
| 304 | 3 | dev@example.com | 2024-03-20 17:15:00+00 | 2024-03-21 09:00:00+00 | 2024-04-04 16:00:00+00 | 91 | US |
EXAMPLE QUERY
WITH recent_conversions AS (
SELECT source, converted_at
FROM marketing.leads
WHERE converted_at >= TIMESTAMPTZ '2024-02-01 00:00:00+00'
)
SELECT
source,
COUNT(*) AS conversions
FROM recent_conversions
GROUP BY source
ORDER BY conversions DESC, source;RESULT — conversions since February 1 by source
| source | conversions |
|---|---|
| google_ads | 1 |
| 1 |
The fixed boundary includes the converted google_ads and linkedin leads, each with one conversion.
This lesson's practice is part of Pro.
Sign up free to try it on a real business scenario