Subqueries &
CTEs
Learn to write queries inside queries and organize complex logic with Common Table Expressions to unlock powerful data analysis.
What Is a Subquery?
A subquery is a SQL query nested inside another SQL query. Think of it as asking a smaller question first, then using its answer to help solve the bigger question.
Where Can Subqueries Go?
Why Do We Need Them?
Many business questions require multi-step reasoning that a single flat query cannot answer. Subqueries let you break complex analysis into logical steps.
The Core Rule of Subqueries
Introducing Common Table Expressions
A CTE (Common Table Expression) is a named, temporary result set defined at the top of a query using the WITH keyword. It makes complex queries readable by giving each logical step a meaningful name.
Anatomy of a CTE
Subquery vs CTE
| Subquery | CTE | |
|---|---|---|
| Syntax | Nested inside parentheses | Defined above with WITH ... AS |
| Readability | Can get messy when deeply nested | Clean, top-down, named blocks |
| Reusability | Must repeat the same subquery | Reference by name multiple times |
| Performance | Usually identical | Usually identical |
| Best For | Simple, one-off filters | Multi-step analytics pipelines |
Scalar vs Table Subqueries
How to Write a Subquery
Example 1: Above-Average Sales
Business question: "Which salespeople exceeded the company's average revenue last quarter?"
Example 2: Customers With Orders
Business question: "List all customers who placed at least one order this month."
Example 3: Multi-Step CTE Pipeline
Business question: "Rank each region's total revenue, then show only regions above the global average."
CTE Execution Flow
Common Mistakes
Question 1 of 5
A subquery that returns exactly one value (one row, one column) is called a:
Question 2 of 5
Which SQL keyword begins a Common Table Expression?
Question 3 of 5
A database has two tables: employees (columns: id, name, dept_id, salary) and departments (columns: id, dept_name). A business analyst writes the following query:
SELECT name FROM employees WHERE dept_id IN (SELECT id FROM departments WHERE dept_name = 'Marketing');
What does the inner subquery return?
Question 4 of 5
What is the main advantage of a CTE over a deeply nested subquery?
Question 5 of 5
An analyst writes: SELECT * FROM (SELECT region, SUM(sales) AS total FROM orders GROUP BY region) WHERE total > 100000;
The database returns an error: "Every derived table must have its own alias."
How should the analyst fix this query?