SQL · Module 05: Subqueries, EXISTS & CTEs (WITH)·Tutorial 13 of 24
5.1 Subqueries: Scalar, Multi-Row (IN / ANY / ALL) & Correlated
Write queries inside queries: understand Scalar vs Multi-Row subqueries, the crucial performance difference between Uncorrelated and Correlated subqueries, and when to replace them with JOINs.
01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs
1. What Is a Subquery? (Nested Query Intuition)
A subquery is simply a SELECT query nested inside parentheses (...) of another query. It lets you answer multi-step questions in one shot — like:
"Find all employees earning more than the company's average salary."
2. The 3 Types of Subqueries (Side-by-Side)
| Type | Returns | Where Used | Example |
|---|---|---|---|
| Scalar Subquery | 1 single value (1 row × 1 col) | WHERE, SELECT, HAVING | WHERE salary > (SELECT AVG(salary) FROM employees) |
| Multi-Row Subquery | 1 column × many rows | WHERE col IN (...), ANY, ALL | WHERE dept_id IN (SELECT id FROM depts WHERE city = 'Pune') |
| Table Subquery (Derived Table) | Multiple rows & columns | FROM (...) AS t | FROM (SELECT dept, AVG(sal) FROM emp GROUP BY dept) t |
SQL
-- 1. Scalar Subquery: Employees earning above company average
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees)
ORDER BY salary DESC;
-- 2. Multi-Row Subquery with ALL: Products pricier than EVERY 'Accessory'
SELECT name, price
FROM products
WHERE price > ALL (
SELECT price FROM products WHERE category = 'Accessory'
);
3. Uncorrelated vs Correlated Subquery (Major Interview Difference!)
| Dimension | Uncorrelated (Independent) Subquery | Correlated Subquery |
|---|---|---|
| References Outer Query? | ❌ No — can be copy-pasted and run standalone | ✅ Yes — references a column like e.dept_id from the outer query |
| How Many Times Does It Run? | Once total (super fast!) | Conceptually once per outer row (O(N × M) if not unnested!) |
| Classic Example | WHERE salary > (SELECT AVG(salary) FROM emp) | WHERE e.salary > (SELECT AVG(salary) FROM emp WHERE dept = e.dept) |
SQL
-- Correlated Subquery: Employees earning above THEIR OWN department's average!
SELECT e.name, e.dept, e.salary
FROM employees e
WHERE e.salary > (
SELECT AVG(e2.salary)
FROM employees e2
WHERE e2.dept = e.dept -- References outer row's e.dept!
);
Watch a Correlated Subquery Evaluate Row-by-Row
Tracing Correlated Subquery (Above Own Dept Average)
Interactive SQL Execution Tracer · Step 1 of 4 (1. Outer Table (employees e))
1SELECT e.name, e.dept, e.salary
2→FROM employees e
3WHERE e.salary > (
4 SELECT AVG(e2.salary) FROM employees e2 WHERE e2.dept = e.dept
5);
Live Table State · 1. Outer Table (employees e)4 rows
| name | dept | salary |
|---|---|---|
| Aarav | Eng | 120000 |
| Kabir | Eng | 160000 |
| Meera | Sales | 70000 |
| Riya | Sales | 110000 |
What the DB engine just did: Eng avg = 140,000; Sales avg = 90,000. Let's test each outer row against its own department's average.
4. Quick Check Your Understanding
Module 5.1 Quick Quiz
Q1.What happens if a Scalar Subquery used with '=' (e.g., WHERE dept_id = (SELECT ...)) accidentally returns 2 rows?
Q2.How do you spot a Correlated Subquery immediately?
Keep Exploring: Related Lessons & Tools
All Courses →DSA Lesson
Graph Fundamentals, BFS & DFS
SQL Lesson
Set Operations: UNION vs UNION ALL, INTERSECT & EXCEPT
PYTHON Lesson
Multithreading, Multiprocessing & asyncio (The GIL Explained)
Free Browser Tool
Big-O & Code Analyzer
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.
Free Browser Tool
Regex Tester & Explainer
Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.