01 / 20

Subqueries &
CTEs

Learn to write queries inside queries and organize complex logic with Common Table Expressions to unlock powerful data analysis.

Business Analytics

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.

SELECT name, salary FROM employees WHERE salary > (-- subquery starts SELECT AVG(salary) FROM employees ); -- subquery ends

Where Can Subqueries Go?

WHERE Clause
Filter rows using a calculated value from another table or aggregation.
FROM Clause
Create a temporary "derived table" that the outer query reads from.
SELECT Clause
Compute a single value per row, like a lookup from another table.

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.

1
Compare to aggregates: "Which products sell above the average price?"
2
Filter across tables: "Show customers who placed at least one order last quarter."
3
Compute derived metrics: "Rank stores by their revenue relative to the regional average."

The Core Rule of Subqueries

OUTER QUERY INNER QUERY (subquery) 1st Executes first 2nd Uses result

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.

WITH avg_salary AS ( SELECT AVG(salary) AS avg_val FROM employees ) SELECT name, salary FROM employees, avg_salary WHERE salary > avg_val;

Anatomy of a CTE

WITH cte_name AS ( SELECT ... FROM ... WHERE ... ) The inner query that defines the CTE's result set Enclosed in parentheses, like a subquery SELECT ... FROM cte_name WHERE ... Main query references the CTE by name Can reference multiple CTEs separated by commas

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

Scalar Subquery
Returns exactly one value (one row, one column). Used with comparison operators like \(=\), \(>\), \(<\).
Table Subquery
Returns multiple rows (or columns). Used with IN, EXISTS, ANY, or in the FROM clause.
-- Scalar: returns one number WHERE price > (SELECT AVG(price) FROM products) -- Table: returns multiple rows WHERE id IN (SELECT product_id FROM orders)

How to Write a Subquery

1
Identify the smaller question: What intermediate result do you need? (e.g., "What is the average salary?")
2
Write the inner query first: Test it alone to make sure it returns the correct result set.
3
Wrap it in parentheses and embed it in the outer query's WHERE, FROM, or SELECT clause.
4
Match the return type: Use \(=\) or \(>\) for scalar subqueries; use IN or EXISTS for table subqueries.
5
Consider refactoring to a CTE if the subquery is reused or the nesting goes deeper than two levels.

Example 1: Above-Average Sales

Business question: "Which salespeople exceeded the company's average revenue last quarter?"

SELECT name, revenue FROM salespeople WHERE revenue > ( SELECT AVG(revenue) FROM salespeople WHERE quarter = 'Q3' ) AND quarter = 'Q3';

Example 2: Customers With Orders

Business question: "List all customers who placed at least one order this month."

SELECT name, email FROM customers WHERE customer_id IN ( SELECT DISTINCT customer_id FROM orders WHERE order_date >= '2024-06-01' );

Example 3: Multi-Step CTE Pipeline

Business question: "Rank each region's total revenue, then show only regions above the global average."

WITH region_rev AS ( SELECT region, SUM(revenue) AS total FROM sales GROUP BY region ), avg_rev AS ( SELECT AVG(total) AS avg_total FROM region_rev ) SELECT r.region, r.total FROM region_rev r, avg_rev a WHERE r.total > a.avg_total ORDER BY r.total DESC;

CTE Execution Flow

CTE 1 region_rev CTE 2 avg_rev Main Query SELECT ... WHERE Aggregates by region Reads from CTE 1 Filters using both CTEs Key Advantage of CTEs Each CTE can reference CTEs defined before it. This creates a clear, top-to-bottom data pipeline that reads like a recipe.

Common Mistakes

✕ Scalar Mismatch
Using = with a subquery that returns multiple rows. Use IN or ANY instead when the inner query returns a list.
✕ Missing Alias
Forgetting to alias a derived table in FROM. Every subquery in FROM needs an alias: (...) AS t.
✕ CTE After SELECT
Placing the WITH clause after the main SELECT. The CTE definition must come before the final SELECT statement.

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

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

How should the analyst fix this query?