CTE vs Subquery in SQL: Which Should You Use?
CTEs (WITH) and subqueries often compile similarly — choose for readability, reuse, and recursion. Clear shop examples for both.
Same idea, different packaging
Both let you answer a question in steps. A subquery nests inside another statement. A CTE names that step up top with WITH.
Subquery — compact scalar check
SELECT name, price FROM products WHERE price > (SELECT AVG(price) FROM products);
Great when the inner result is a single value used once.
CTE — named steps you can reread
WITH paid AS ( SELECT * FROM orders WHERE status = 'paid' ) SELECT c.first_name, p.order_id FROM paid p JOIN customers c ON c.customer_id = p.customer_id;
Prefer CTEs when the query has several clear steps — naming each step makes the shop logic easier to follow.
Practical rule of thumb
- One-off scalar → subquery is fine
- Reuse intermediate result → CTE
- Recursion → CTE only
- Need indexes across several statements → temp table (different tool)
FAQ
Are CTEs faster than subqueries?
Usually not meaningfully. Modern engines treat them similarly. Pick the shape that’s easier to read and maintain.
When must I use a CTE?
Recursive queries need WITH RECURSIVE. CTEs also shine when you reuse the same intermediate result twice in one query.
Try it yourself
The fastest way to lock this in is a short drill on the same Northstar Market tables.