Skip to main content
Albero Academy

SQL Subqueries & CTEs

Master subqueries and Common Table Expressions (WITH) — when to use which, recursive CTEs, and writing readable analytical SQL.

Chapter 4SQL16 min readBeginner friendly
  • #SQL
  • #Subqueries
  • #CTEs
  • #WITH

Subqueries and CTEs are how you compose SQL — wrap one query inside another to build up complex analyses step by step. Modern analytics SQL leans heavily on CTEs because they read top-to-bottom like a script.

Scalar & inline subqueries

Scalar subquery — returns one value

SQL
-- Show every employee's salary alongside the company average
SELECT name,
salary,
(SELECT AVG(salary) FROM employees) AS company_avg
FROM employees;

Inline subquery — used like a table

SQL
-- Top-3 highest-paid employees per department
SELECT *
FROM (
SELECT name, department, salary,
DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rk
FROM employees
) t
WHERE rk <= 3;

IN, EXISTS, ANY, ALL

SQL
-- Customers who placed at least one order over ₹10,000
SELECT name FROM customers c
WHERE c.id IN (
SELECT customer_id FROM orders WHERE amount > 10000
);
-- Same logic with EXISTS — usually faster on large tables
SELECT name FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.id AND o.amount > 10000
);
-- ALL — bigger than every value in the subquery
SELECT name, salary FROM employees
WHERE salary > ALL (
SELECT salary FROM employees WHERE department = 'Sales'
);

Common Table Expressions (WITH)

A CTE is a named subquery you define before the main query. It reads top-to-bottom like a workflow:

SQL
WITH dept_avg AS (
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
),
ranked AS (
SELECT e.name, e.department, e.salary, d.avg_salary,
e.salary - d.avg_salary AS diff_from_avg
FROM employees e
JOIN dept_avg d ON d.department = e.department
)
SELECT *
FROM ranked
WHERE diff_from_avg > 0
ORDER BY diff_from_avg DESC;

CTE vs subquery — when to choose

Use a CTE whenUse a subquery when
Reusing the result more than onceIt's used in exactly one place
You want named, readable stepsThe logic is simple and inline
Building up a multi-step analysisYou're returning a single scalar value
Recursing (CTEs only)Performance is critical (engine-dependent)

Recursive CTEs

Useful for hierarchies — org charts, comment threads, file folder trees, BOM (bill of materials).

SQL
-- Find the entire reporting chain under CEO id = 1
WITH RECURSIVE org AS (
-- Anchor: start with the CEO
SELECT id, name, manager_id, 1 AS level
FROM employees
WHERE id = 1
UNION ALL
-- Recursive: every employee whose manager is in the previous level
SELECT e.id, e.name, e.manager_id, o.level + 1
FROM employees e
INNER JOIN org o ON e.manager_id = o.id
)
SELECT level, name FROM org ORDER BY level, name;

Key takeaways

  1. 01Scalar subqueries return one value; inline subqueries act as virtual tables.
  2. 02EXISTS short-circuits — usually faster than IN on big tables.
  3. 03CTEs (WITH) make multi-step analytics queries readable top-to-bottom.
  4. 04CTEs let you name and reuse intermediate results — much cleaner than nesting subqueries.
  5. 05Recursive CTEs handle hierarchies — anchor + recursive member joined by UNION ALL.