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
-- Show every employee's salary alongside the company averageSELECT name,salary,(SELECT AVG(salary) FROM employees) AS company_avgFROM employees;
Inline subquery — used like a table
-- Top-3 highest-paid employees per departmentSELECT *FROM (SELECT name, department, salary,DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rkFROM employees) tWHERE rk <= 3;
IN, EXISTS, ANY, ALL
-- Customers who placed at least one order over ₹10,000SELECT name FROM customers cWHERE c.id IN (SELECT customer_id FROM orders WHERE amount > 10000);-- Same logic with EXISTS — usually faster on large tablesSELECT name FROM customers cWHERE EXISTS (SELECT 1 FROM orders oWHERE o.customer_id = c.id AND o.amount > 10000);-- ALL — bigger than every value in the subquerySELECT name, salary FROM employeesWHERE 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:
WITH dept_avg AS (SELECT department, AVG(salary) AS avg_salaryFROM employeesGROUP BY department),ranked AS (SELECT e.name, e.department, e.salary, d.avg_salary,e.salary - d.avg_salary AS diff_from_avgFROM employees eJOIN dept_avg d ON d.department = e.department)SELECT *FROM rankedWHERE diff_from_avg > 0ORDER BY diff_from_avg DESC;
CTE vs subquery — when to choose
| Use a CTE when | Use a subquery when |
|---|---|
| Reusing the result more than once | It's used in exactly one place |
| You want named, readable steps | The logic is simple and inline |
| Building up a multi-step analysis | You'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).
-- Find the entire reporting chain under CEO id = 1WITH RECURSIVE org AS (-- Anchor: start with the CEOSELECT id, name, manager_id, 1 AS levelFROM employeesWHERE id = 1UNION ALL-- Recursive: every employee whose manager is in the previous levelSELECT e.id, e.name, e.manager_id, o.level + 1FROM employees eINNER JOIN org o ON e.manager_id = o.id)SELECT level, name FROM org ORDER BY level, name;
Key takeaways
- 01Scalar subqueries return one value; inline subqueries act as virtual tables.
- 02EXISTS short-circuits — usually faster than IN on big tables.
- 03CTEs (WITH) make multi-step analytics queries readable top-to-bottom.
- 04CTEs let you name and reuse intermediate results — much cleaner than nesting subqueries.
- 05Recursive CTEs handle hierarchies — anchor + recursive member joined by UNION ALL.
