Scalar subquery: one value
-- Products priced above the average price
SELECT name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products)
ORDER BY price DESC;| name | price |
|---|---|
| Smartwatch | 4999.00 |
| Bluetooth Speaker | 2499.00 |
| Headphones | 1999.00 |
The inner query calculates the average price once (about 1,932); the outer query compares every product with it.
IN subquery: a list
-- Customers who bought a Smartwatch
SELECT name
FROM customers
WHERE customer_id IN (
SELECT o.customer_id
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE oi.product_id = 3
)
ORDER BY name;| name |
|---|
| Arjun |
| Imran |
| Meera |
| Priya |
| Rahul |
Correlated subquery: once per row
-- For each customer, their latest order date (runs once per customer row)
SELECT c.name,
(SELECT MAX(o.order_date)
FROM orders o
WHERE o.customer_id = c.customer_id) AS last_order
FROM customers c
ORDER BY c.customer_id;| name | last_order |
|---|---|
| Asha | 2026-05-02 |
| Rahul | 2026-05-11 |
| Priya | 2026-05-04 |
| Imran | 2026-05-09 |
| Meera | 2026-05-28 |
| Arjun | 2026-05-20 |
| Sara | NULL |
| Vikram | 2026-05-22 |
The inner query uses c.customer_id from the outer row, so it runs for each customer. Sara has no orders, so her result is NULL. On big tables, a JOIN with GROUP BY or a window function is usually faster.
CTEs: queries that read like steps
Question: which customers spend more than the average customer (on delivered orders)? Three steps:
delivered_totals
Total of each delivered order
customer_spend
Add up per customer
Final SELECT
Keep those above the average
WITH delivered_totals AS ( -- step 1: total per delivered order
SELECT o.customer_id,
SUM(oi.quantity * oi.unit_price) AS order_total
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status = 'DELIVERED'
GROUP BY o.order_id, o.customer_id
),
customer_spend AS ( -- step 2: total per customer
SELECT customer_id, SUM(order_total) AS spend
FROM delivered_totals
GROUP BY customer_id
)
SELECT c.name, s.spend -- step 3: customers above average spend
FROM customer_spend s
JOIN customers c ON c.customer_id = s.customer_id
WHERE s.spend > (SELECT AVG(spend) FROM customer_spend)
ORDER BY s.spend DESC;| name | spend |
|---|---|
| Asha | 8092.00 |
| Imran | 7497.00 |
| Rahul | 6298.00 |
| Meera | 6298.00 |
| Arjun | 6195.00 |
Each CTE can use the ones above it. Compare this with three nested subqueries: same result, much harder to read and debug. In data engineering (and dbt), almost every transformation is written as a chain of CTEs.
Recursive CTE: walking a hierarchy
How many levels does ShopKart's org chart have? You don't know in advance, so you can't write a fixed number of self joins. A recursive CTE starts with the top person and keeps adding the next level until no rows are left:
WITH RECURSIVE org AS (
SELECT emp_id, name, manager_id, 1 AS level, name::text AS path
FROM employees
WHERE manager_id IS NULL -- start: the top boss
UNION ALL
SELECT e.emp_id, e.name, e.manager_id, org.level + 1,
org.path || ' โ ' || e.name
FROM employees e
JOIN org ON e.manager_id = org.emp_id -- repeat: people reporting to the last level
)
SELECT level, name, path
FROM org
ORDER BY path;| level | name | path |
|---|---|---|
| 1 | Kavya | Kavya |
| 2 | Neha | Kavya โ Neha |
| 3 | Farhan | Kavya โ Neha โ Farhan |
| 3 | Ishaan | Kavya โ Neha โ Ishaan |
| 3 | Pooja | Kavya โ Neha โ Pooja |
| 2 | Rohan | Kavya โ Rohan |
| 3 | Amit | Kavya โ Rohan โ Amit |
| 3 | Divya | Kavya โ Rohan โ Divya |
| 3 | Karan | Kavya โ Rohan โ Karan |
- Anchor (before UNION ALL): the starting rows, here the boss with no manager.
- Recursive part (after): joins the CTE to the table to get the next level.
- It stops when a step returns no new rows. Uses: org charts, category trees, bill of materials, date series.
Set operations: UNION, INTERSECT, EXCEPT
SELECT 'customer' AS person_type, name FROM customers WHERE city = 'Kolkata'
UNION ALL
SELECT 'employee', name FROM employees WHERE department = 'Data'
ORDER BY person_type, name;| person_type | name |
|---|---|
| customer | Arjun |
| customer | Asha |
| employee | Amit |
| employee | Divya |
| employee | Karan |
| employee | Rohan |
SELECT
(SELECT COUNT(*) FROM (SELECT city FROM customers UNION SELECT city FROM customers) u) AS union_rows,
(SELECT COUNT(*) FROM (SELECT city FROM customers UNION ALL SELECT city FROM customers) a) AS union_all_rows;| union_rows | union_all_rows |
|---|---|
| 6 | 16 |
8 cities + 8 cities = 16 rows with UNION ALL, but only 6 distinct values (5 cities and NULL) with UNION.
-- Product ids that exist but were never ordered
SELECT product_id FROM products
EXCEPT
SELECT product_id FROM order_items;| product_id |
|---|
| 6 |
| Operator | Returns |
|---|---|
| UNION ALL | All rows from both (fastest) |
| UNION | All rows, duplicates removed |
| INTERSECT | Rows in both queries |
| EXCEPT (MINUS in Oracle) | Rows in the first but not the second |
Both queries must return the same number of columns with compatible types; column names come from the first query.
๐ฏ Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1Difference between a subquery and a CTE?Fresher+
Q2EXISTS vs IN?1โ3 yrs+
Q3How would you find the hierarchy level of every employee?1โ3 yrs+
Q4UNION vs UNION ALL, and which do you use in pipelines?1โ3 yrs+
Q5Can a CTE hurt performance?3+ yrs+
Key takeaways
- โSubqueries and CTEs split a problem into steps.
- โCTEs make complex SQL readable: the standard style for pipelines.
- โRecursive CTEs handle hierarchies of any depth.
- โNext: window functions, the most important interview topic.
Frequently asked questions
What is a subquery?
A query inside another query, in brackets. It can return one value (scalar), a list (used with IN), or a table (used in FROM).
What is a CTE?
A Common Table Expression: a named, temporary result defined with WITH name AS (...) at the top of a query. It makes long queries readable, step by step, like variables in code.
CTE or subquery: which is faster?
Usually the same: modern databases optimise them alike. Choose CTEs for readability. A CTE used several times may be computed once or inlined, depending on the database.
What is a correlated subquery?
A subquery that refers to the outer query's row, so it conceptually runs once per row. Powerful but can be slow on big tables; often a JOIN or window function is better.
UNION or UNION ALL?
UNION removes duplicate rows (extra sorting work); UNION ALL keeps everything and is faster. Use UNION ALL unless you need duplicates removed.
๐ง Quick check: subqueries and CTEs
1. WHERE price > (SELECT AVG(price) FROM products) uses a...
2. Which is used to walk an employee โ manager hierarchy of unknown depth?
3. UNION of two lists with 8 rows each and many repeats returns...
4. EXCEPT returns...
Checking your accessโฆ