Skip to main content
Albero Academy

Subqueries & CTEs

Nest a query inside another, correlate it to the outer row, and refactor complex logic into readable common table expressions.

Chapter 6MySQL16 min readBeginner friendly
  • #MySQL
  • #Subqueries
  • #CTEs

A subquery is a SELECT nested inside another statement — a way to answer "compared to a value that itself needs a query". CTEs (common table expressions) give the same power a readable name. Together they let you express logic that a single flat query can't.

A query inside a query

above the average
-- Students earning more than the overall average package
SELECT name, package FROM students
WHERE package > (SELECT AVG(package) FROM students);

Where subqueries go

  • In WHERE — compare against a computed value or a list with IN/EXISTS.
  • In FROM — a derived table you then query further.
  • In SELECT — a scalar value per row (use sparingly; it can be slow).
IN and a derived table
-- Students in programmes based in Pune
SELECT name FROM students
WHERE programme_id IN (SELECT id FROM programmes WHERE city = 'Pune');
-- Derived table: average package per programme, then filter
SELECT * FROM (
SELECT programme_id, AVG(package) AS avg_pkg
FROM students GROUP BY programme_id
) t
WHERE t.avg_pkg > 7;

Correlated subqueries

A correlated subquery references the outer row, so it re-runs for each one. EXISTS is the classic use — often clearer and faster than a big IN list:

does a match exist?
-- Programmes that have at least one placed student
SELECT p.name FROM programmes p
WHERE EXISTS (
SELECT 1 FROM students s
WHERE s.programme_id = p.id AND s.status = 'placed'
);

CTEs with WITH

A common table expression names a query up front so the main query reads top-to-bottom. It's the cure for deeply nested subqueries:

the same logic, readable
WITH prog_stats AS (
SELECT programme_id, AVG(package) AS avg_pkg, COUNT(*) AS n
FROM students GROUP BY programme_id
)
SELECT p.name, ps.avg_pkg, ps.n
FROM prog_stats ps
JOIN programmes p ON p.id = ps.programme_id
WHERE ps.n >= 5
ORDER BY ps.avg_pkg DESC;

Recursive CTEs

A WITH RECURSIVE CTE walks a hierarchy (org chart, category tree) by repeatedly joining its own output:

walking a hierarchy
WITH RECURSIVE chain AS (
SELECT id, name, manager_id FROM employees WHERE id = 1 -- start (anchor)
UNION ALL
SELECT e.id, e.name, e.manager_id
FROM employees e JOIN chain c ON e.manager_id = c.id -- recurse
)
SELECT * FROM chain;

Practice

Rewrite an "above-average package" query with a subquery, then as a CTE. Use EXISTS to list programmes with at least one placed student. Build a derived table of average package per programme and filter it. If you have a manager column, write a recursive CTE that lists a management chain.

Key takeaways

  1. 01A subquery is a SELECT nested in WHERE, FROM (derived table) or SELECT (scalar).
  2. 02IN checks membership; EXISTS checks whether any matching row exists — often faster.
  3. 03A correlated subquery references the outer row and runs per row.
  4. 04A CTE (WITH name AS …) names a query up front so complex logic reads top-to-bottom.
  5. 05WITH RECURSIVE walks hierarchies and trees by repeatedly joining its own output.