Loading…
Loading…
Charting your lesson…
Opening your lesson…
Subqueries, Views and CTEs
Lesson 4 of 4
6 steps•about 12 min•12 flashcards
Step 1/ 61 min
Complex questions often need a query inside a query, or a reusable named result. Subqueries, views and CTEs are the three tools for composing SQL — and knowing when each fits (and the correlated-subquery performance trap) marks a competent SQL author.
Core idea: a subquery is a query nested inside another (in WHERE, FROM, or SELECT). A view is a saved named query you can query like a table. A CTE (Common Table Expression, WITH) is a temporary named result defined for a single statement — improving readability and enabling recursion.
Step 2/ 61 min
-- rows where salary beats the company average
SELECT name FROM Employee
WHERE salary > (SELECT AVG(salary) FROM Employee); -- scalar subquery
A scalar subquery returns one value; an IN subquery returns a column of values; an EXISTS subquery tests for any matching row.
-- correlated: for EACH employee, compare to their OWN department's average
SELECT name FROM Employee e
WHERE salary > (SELECT AVG(salary) FROM Employee
WHERE dept_id = e.dept_id); -- references outer e -> correlated
A view persists a query definition in the schema:
CREATE VIEW HighEarners AS
SELECT name, dept_id FROM Employee WHERE salary > 100000;
SELECT * FROM HighEarners WHERE dept_id = 3; -- query it like a table
Views give abstraction (hide complexity), security (expose only some columns), and reusability; most are read-only for querying, though simple ones can be updatable. A CTE is scoped to one statement and reads top-to-bottom, which untangles nested subqueries — and uniquely supports recursion (hierarchies, graphs):
WITH RECURSIVE Chain AS (
SELECT id, manager_id FROM Employee WHERE id = 7 -- anchor
UNION ALL
SELECT e.id, e.manager_id
FROM Employee e JOIN Chain c ON e.manager_id = c.id -- recursive step
)
SELECT * FROM Chain; -- whole reporting tree
Step 3/ 61 min
Find departments whose average salary exceeds the overall company average.
WITH dept_avg AS (
SELECT dept_id, AVG(salary) AS a FROM Employee GROUP BY dept_id
)
SELECT dept_id, a FROM dept_avg
WHERE a > (SELECT AVG(salary) FROM Employee);
The CTE dept_avg names the per-department averages once, so the final query reads plainly. Writing the same logic as a subquery in the FROM clause works identically but nests the grouping inside parentheses, which is harder to follow and can't be referenced twice. CTEs shine when a derived table is used multiple times or the logic is layered.
Step 4/ 61 min
Common asks: "difference between a subquery and a join" (often interchangeable; joins usually faster), "correlated vs non-correlated subquery and its performance", "view vs CTE" (persistent schema object vs single-statement temporary), and "how do you query a hierarchy" (recursive CTE). EXISTS vs IN (and NULL behaviour of NOT IN) is a frequent trap.
Step 5/ 61 min
NOT IN with a subquery that yields any NULL returns no rows (the comparison becomes unknown) — prefer NOT EXISTS.Using NOT IN (subquery) when the subquery can return NULL. If the list contains a NULL, x NOT IN (…, NULL) evaluates to UNKNOWN for every x, so the outer query returns zero rows — a silent, baffling bug. Use NOT EXISTS (which handles NULLs correctly) or filter NULLs out of the subquery.
WHERE/FROM/SELECT; scalar, IN, and EXISTS forms exist.WITH) is a single-statement temporary result; WITH RECURSIVE handles hierarchies.NOT IN with NULLs breaks; prefer NOT EXISTS.NOT IN NULLs.Step 6/ 6· Worked examples2 min
Problem
From Employees(id, name, dept_id, salary), write three equivalent-in-spirit solutions to "list employees earning more than their department's average salary": (a) a correlated subquery, (b) a CTE, and explain how a view would package it. Contrast a correlated vs non-correlated subquery.
Try it on paper first.
Recall
Keep this
Subqueries, views, and CTEs are the "intermediate SQL" the interviewer uses to gauge depth. "Correlated vs non-correlated subquery" and "view vs materialized view" are common, along with rewriting a nested query as a CTE.
A subquery is a query nested inside another. A non-correlated subquery runs once, independent of the outer query. A correlated subquery references the outer row and runs once per outer row (slower). Subqueries appear in WHERE, FROM (derived table), or SELECT.
A view is a virtual table defined by a stored query — it stores no data, just the definition, and runs fresh each time. A materialized view stores the result physically and must be refreshed — faster reads, but potentially stale.
A CTE (WITH name AS (...)) is a named temporary result set that exists for one query. It improves readability over nested subqueries and can be recursive (for hierarchies/trees).
| Feature | Stores data | Scope |
|---|---|---|
| View | no | persistent object |
| Materialized view | yes | persistent + refresh |
| CTE | no | single query |
WITH) improves readability and enables recursion for tree/hierarchy traversal.IN/ANY/ALL, not = — using = errors."Correlated vs non-correlated subquery", "view vs materialized view", "what is a CTE / recursive CTE?", "are views updatable?", and rewriting a subquery as a CTE.
Subquery = nested query; correlated ones reference the outer row and run per row (slower). View = virtual table storing only the definition; materialized view stores results (refresh needed). CTE (WITH) = named single-query temp result, readable and recursion-capable. Multi-row subqueries need IN/ANY/ALL.
You've read 0 of 6 steps
Now lock it in — questions straight after reading are what make it stick.