CTE vs Subquery: When to Use Which in SQL
By Sharon Ben-Moshe · June 25, 2026 · 4 min read
Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
CTE vs subquery comes down to readability, reuse, and recursion. Here's when each one wins, plus the PostgreSQL optimization-fence gotcha you should know.
Quick answer
Use a CTE (WITH clause) when a query is complex, references the same result more than once, or needs recursion — it reads top-to-bottom and names each step. Use a subquery for simple, one-off, or correlated lookups where naming a separate step adds nothing. On modern engines they usually perform identically, so choose based on readability.