Chapter 7 · 6 levels
Subqueries and CTEs
Build queries in steps: scalar subqueries, EXISTS, CTEs with WITH, pre-aggregation to avoid fan-out, deduplication and a first retention analysis.
StartSome questions cannot be answered in one pass. “Products priced above average” needs the average first. “Customer lifetime value” needs revenue per order, then per customer. “Repeat rate” needs each customer’s first order before you can look at what came after it.
Subqueries and common table expressions (CTEs) let you build an answer in named steps, each one a small query you can run and check on its own. That is how analysts write the long queries behind dashboards, and how interviewers expect you to structure a multi-step problem. The boss level is a first-order and repeat-purchase analysis.
Levels
- Products priced above average
from Jessica Turner, Merchandising Manager
subquery, scalar subquery, avg
- Customers who returned something
from Rachel Adams, Customer Support Lead
exists, in subquery, not in null, semi join
- Customer lifetime value
from Lauren Hayes, Email Marketing Manager
cte, with, multi step, average order value, lifetime value
- Shipping and merchandise revenue per channel
from Brian Mitchell, Finance Analyst
cte, fan out, pre aggregation, left join, coalesce
- Find duplicate customer records
from Tyler Morgan, Junior Data Engineer
duplicates, having, normalization, data quality
- Boss: first orders and repeat purchases
from Megan Collins, Head of Sales
cte, min, exists, retention, cohort