When would you use a subquery or common table expression instead of another join?
Answer
A subquery can express existence, scalar lookup or set membership, while a common table expression gives a named intermediate result that can make a complex query easier to read and test. A join is often clearer when combining related row sets, but equivalent syntax does not guarantee an identical plan on every database. Verify empty and multi-row cases, NULL behaviour in IN or NOT IN, duplicate amplification, recursive termination and the actual execution plan for performance-sensitive queries.
Strong answer includes
- chooses syntax for semantics and clarity
- recognizes NULL and cardinality traps
- does not assume equivalent syntax has identical performance
Practical example
Runs against the resettable SQLite sample database used by the playground.
Run the query to see the result.
The CTE isolates the aggregation and gives it a name before it is joined to customer data. This often makes complex logic easier to reason about and test independently than deeply nested subqueries.
Expected result: Customers in the sample database whose paid-order total exceeds 150.