Subqueries and CTEs
Some questions need multiple steps: "Find products priced above the average price." First compute the average, then compare. Subqueries and CTEs let you build queries out of other queries.
Subquery in WHERE
The inner query runs first and returns a single value.
Subquery with IN
EXISTS
EXISTS checks whether a subquery returns any row. It's often faster than IN on large tables, and it's the clearest way to say "has at least one…".
This is a correlated subquery: it refers to c from the outer query, so it's evaluated per customer.
Subquery in FROM (derived table)
CTEs: WITH for readable queries
A Common Table Expression names a subquery up front, like a variable. Long reports become a series of readable steps.
Pro tip: when a query grows past ~15 lines, break it into CTEs. Each step can be tested on its own by changing the final
SELECT.
Recursive CTEs
A CTE can refer to itself. It's useful for sequences, org charts and category trees.
UNION
UNION stacks results from two queries with the same columns (UNION ALL keeps duplicates and is faster).
Practice
Using a CTE, find the best-selling product (by total quantity) in each category.
1.What is a correlated subquery?
2.Why use a CTE instead of nested subqueries?