// free study notes

SQL subquery & CTE interview questions

From scalar subqueries to recursive CTEs, including the NOT IN versus NULL trap: one NULL in the subquery and the query returns nothing.

12 questions
  • 4 easy
  • 7 medium
  • 1 hard
Practice mode: all topics, shuffled

What this page covers

  • 12 questions on subqueries & CTEs, tagged easy, medium or hard, each with a worked answer in runnable SQL.
  • One schema throughout. The answers use the small shop schema shown here. Dialect-specific examples name the engine they are written for, and the few extra tables a question needs, such as subscribers or logins, are introduced where they appear.
  • Practice mode. To test yourself first, press Hide answers: each answer waits behind a Show answer button. The practice mode link deals a shuffled deck from every topic.
The shop schema
customers(customer_id, name, city, signup_date)
orders(order_id, customer_id, order_date, status, total)
order_items(order_id, product_id, quantity, unit_price)
products(product_id, name, category, price)
employees(employee_id, name, manager_id, department, salary, hired_on)

The questions

What is a scalar subquery, and where can it appear?

Easy

A subquery that returns exactly one row and one column, usable anywhere a single value is allowed: the SELECT list, WHERE comparisons, even ORDER BY.

SELECT name,
(SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.customer_id) AS order_count
FROM customers c;

Two follow-ups. If the subquery returns more than one row, PostgreSQL, SQL Server, MySQL and Oracle raise a runtime error, while SQLite silently uses the first row; if it returns no rows, the value is NULL, so a COUNT subquery is safe but a SUM one may need COALESCE. And a correlated scalar subquery is logically evaluated once per outer row: some optimizers turn it into a join, PostgreSQL generally does not, so on large tables a LEFT JOIN to a grouped subquery is often faster.

What is the difference between IN and EXISTS?

Easy

IN tests membership against a list the subquery returns. EXISTS tests whether the correlated subquery returns any row, and short-circuits at the first match. Modern optimizers rewrite both into the same semi-join in most cases, but they differ in two ways: NULL semantics and what you can express.

-- IN: explicit list membership
SELECT * FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders WHERE total > 500);

-- EXISTS: first match wins, no list materialized
SELECT * FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id AND o.total > 500);

EXISTS can correlate on any condition, such as o.total > c.credit_limit, while IN only tests equality against a list. The NULL trap of NOT IN does not apply to NOT EXISTS. Inside EXISTS the select list is ignored, so SELECT 1 and SELECT * perform the same; SELECT 1 just tells the reader that only existence matters.

Write a correlated subquery: return orders above the average for their own customer.

Médio

The inner query references the outer row, so it computes a different average per customer.

SELECT o.order_id, o.customer_id, o.total
FROM orders o
WHERE o.total > (
SELECT AVG(o2.total)
FROM orders o2
WHERE o2.customer_id = o.customer_id
);

Say what correlated means: the subquery cannot run once on its own; it re-runs (or is rewritten to a join) per outer row. The window-function version computes AVG(total) OVER (PARTITION BY customer_id) AS customer_avg in a subquery and filters total > customer_avg outside it; it reads orders once instead of once per customer, which usually wins at scale.

Why can NOT IN return no rows when the subquery contains a NULL?

Médio

x NOT IN (a, b, NULL) can never be true: if x equals a or b the result is false, and if it equals neither, the comparison with NULL is unknown. A WHERE clause keeps only true rows, so everything is filtered out.

-- Returns zero rows if any orders.customer_id is NULL:
SELECT * FROM customers c
WHERE c.customer_id NOT IN (SELECT o.customer_id FROM orders o);

-- Safe: NULLs do not match, so they are simply skipped:
SELECT * FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);

The defense: filter NULLs explicitly (WHERE o.customer_id IS NOT NULL inside the subquery), make the column NOT NULL in the schema, or use NOT EXISTS. The bug is nasty because the query works for months and then returns nothing the day one guest order with a NULL customer_id is inserted.

What is a derived table, and when is one needed?

Easy

A subquery in the FROM clause: an inline view that materializes (or is rewritten as) an intermediate result you can query like a table. You need one whenever a later step must filter or join on a value computed in an earlier step, such as a window function result.

SELECT city, avg_spend
FROM (
SELECT c.city, AVG(o.total) AS avg_spend
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.city
) city_stats
WHERE avg_spend > 100;

WHERE cannot filter on AVG directly because aggregates do not exist until after grouping. Here HAVING AVG(o.total) > 100 would do the same job without a derived table; the derived table earns its place when you filter on a window function or join one aggregate to another. The alias (city_stats) is required by PostgreSQL before 16, MySQL and SQL Server. Optimizers usually merge simple derived tables into the outer query, so there is no automatic performance penalty.

What is a CTE, and why use one instead of a subquery?

Médio

A WITH clause defines a named, temporary result visible for the duration of one statement. It improves readability, lets one definition be referenced several times, and is the only syntax for recursion.

-- PostgreSQL date truncation; the CTE syntax itself is portable:
WITH monthly AS (
SELECT DATE_TRUNC('month', order_date) AS month, SUM(total) AS revenue
FROM orders
GROUP BY 1
),
best AS (
SELECT month, revenue,
ROW_NUMBER() OVER (ORDER BY revenue DESC) AS rn
FROM monthly
)
SELECT month, revenue FROM best WHERE rn <= 3;

The performance note: a CTE is for readability, not speed. PostgreSQL before 12 always materialized CTEs, which blocked filters from being pushed inside; since 12 it inlines a CTE referenced once, and you can force either behavior with MATERIALIZED or NOT MATERIALIZED. SQL Server never materializes a CTE, so one referenced twice is computed twice; when that is expensive, a temporary table is the fix.

Write a recursive CTE that walks the employee manager hierarchy.

Hard

A recursive CTE has an anchor member (the top of the hierarchy) and a recursive member that joins the CTE to itself until it returns no rows.

WITH RECURSIVE chain AS (
-- anchor: the CEO
SELECT employee_id, name, manager_id, 0 AS level
FROM employees
WHERE manager_id IS NULL

UNION ALL

-- recursive: one level down each iteration
SELECT e.employee_id, e.name, e.manager_id, c.level + 1
FROM employees e
JOIN chain c ON e.manager_id = c.employee_id
)
SELECT * FROM chain ORDER BY level;

SQL Server and Oracle write plain WITH; PostgreSQL, MySQL 8+ and SQLite require WITH RECURSIVE. If the data contains a cycle (A manages B, B manages A), UNION ALL keeps producing rows: PostgreSQL and SQLite loop until you cancel, SQL Server stops with an error after 100 levels (OPTION (MAXRECURSION n) changes that), and MySQL stops at cte_max_recursion_depth, 1000 by default. The fix is to carry the path of visited ids and stop when the next id is already in it, or use PostgreSQL 14's CYCLE clause.

Return the second-highest salary per department. Show two ways.

Médio

The window way and the offset way. Both handle ties differently, which is the discussion the interviewer wants.

-- Way 1: DENSE_RANK keeps ties together, so two people sharing
-- the top salary both count as rank 1 and rank 2 is the next value:
SELECT department, name, salary
FROM (
SELECT name, department, salary,
DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk
FROM employees
) ranked
WHERE rnk = 2;

-- Way 2: DISTINCT salaries, skip one with OFFSET:
SELECT DISTINCT department, salary
FROM employees e
WHERE salary = (
SELECT DISTINCT salary
FROM employees e2
WHERE e2.department = e.department
ORDER BY salary DESC
LIMIT 1 OFFSET 1
);

State the tie question out loud: does the interviewer want the second-highest distinct salary, or the person in second place? Both queries above answer the first; ROW_NUMBER answers the second. A department with only one distinct salary returns no row from either query, which is correct rather than broken. Way 2 uses LIMIT ... OFFSET; SQL Server writes ORDER BY salary DESC OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY.

What is a semi-join, and how do you write one?

Médio

A semi-join returns rows from the left side that have at least one match on the right, without duplicating left rows or needing right-side columns. SQL spells it as IN or EXISTS.

-- Customers who ordered in March, once each, no order columns needed:
SELECT c.name
FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.customer_id
AND o.order_date >= '2025-03-01' AND o.order_date < '2025-04-01'
);

The contrast with a plain join: joining customers to March orders duplicates a customer once per March order, forcing DISTINCT to undo the fan-out. EXISTS states the intent (has at least one match) and lets the optimizer choose a fast semi-join plan, often a hash or index probe with early termination.

When can the optimizer flatten a subquery into a JOIN, and when not?

Médio

Simple cases flatten: uncorrelated derived tables, IN and EXISTS subqueries the planner can rewrite to semi-joins. Subqueries containing LIMIT, aggregates whose result depends on the outer row, and recursive CTEs often cannot be flattened, so they run once per outer row or are materialized first. How far each optimizer goes differs: SQL Server decorrelates many scalar subqueries into joins, while PostgreSQL runs a correlated scalar subquery as a SubPlan per row.

-- Becomes a semi-join (hash or merge) in most engines:
SELECT c.name FROM customers c
WHERE c.customer_id IN (SELECT customer_id FROM orders WHERE total > 500);

-- Per-row execution risk: scalar correlated subquery in SELECT:
SELECT name,
(SELECT MAX(total) FROM orders o WHERE o.customer_id = c.customer_id) AS max_total
FROM customers c;

The practical point: read the plan rather than assume. In PostgreSQL a SubPlan node executed once per outer row is the signal to rewrite as a LEFT JOIN to a grouped subquery, or as a window function. The rewrite of the example: LEFT JOIN (SELECT customer_id, MAX(total) AS max_total FROM orders GROUP BY customer_id) m ON m.customer_id = c.customer_id.

How does a subquery in FROM differ from a view?

Médio

A derived table lives inside one statement; a view is a named query stored in the database, so many queries can reuse it and you can grant access to the view without granting access to the tables behind it.

CREATE VIEW monthly_revenue AS
SELECT DATE_TRUNC('month', order_date) AS month, SUM(total) AS revenue
FROM orders
GROUP BY 1;

SELECT * FROM monthly_revenue WHERE revenue > 10000;

Worth adding: a plain view stores no data. The optimizer expands it into the query like a derived table, so it is no faster than the SQL it contains. Materialized views (PostgreSQL, Oracle) store the result and must be refreshed; SQL Server's indexed views store it too and are kept up to date on every write. Views also give a stable interface: you can restructure the tables behind one without breaking the reports that query it.

What does the IN operator with a literal list do, and what are its edge behaviors with NULL?

Easy

x IN (1, 2, 3) is shorthand for x = 1 OR x = 2 OR x = 3. With NULL in the list, matching rows still match, but non-matching rows become unknown instead of false, so NOT IN flips to empty results.

-- Rows whose status is completed or shipped:
SELECT * FROM orders WHERE status IN ('completed', 'shipped');

-- Returns no rows at all: for every row, status <> NULL is
-- unknown, so the whole NOT IN can never be true:
SELECT * FROM orders WHERE status NOT IN ('completed', 'shipped', NULL);

Nobody types NULL into a literal list on purpose; it arrives through a parameter or an application-built list. Rows whose own status is NULL drop out of both IN and NOT IN, because NULL = 'completed' is unknown too. The rule: IN is safe for positive filters, NOT IN needs a guarantee that neither the column nor the list contains NULL.

Subqueries & CTEs interview FAQ

What is the difference between IN and EXISTS?

IN checks a value against the list a subquery returns; EXISTS checks whether a correlated subquery returns any row at all. The answers cover both, including the semi-join reading of EXISTS and why NOT IN with a NULL in the subquery returns zero rows while NOT EXISTS does not.

Is there a recursive CTE question?

Yes: walk an employee manager hierarchy with a recursive CTE, the anchor-plus-recursive-member structure spelled out line by line.

Do the answers cover correlated subqueries?

Several. The headline one returns every order that is above the average for its own customer, and a later one finds the second-highest salary per department two different ways.

When should a subquery become a JOIN?

There is a dedicated answer on when the optimizer can flatten a subquery into a join, when it cannot, and what that means for the plan you get.

Other topics

// from study notes to daily tool

Now write some SQL against a real database

SQLly is a native SQL workbench for macOS, Windows and Linux: IntelliSense that knows your schema, a formatter, guardrails for risky queries, and every engine in one app.