Databases & SQL interview questions on subqueries

Reviewed by Mark Dickie · Last updated

5 questions on this page you can answer and see marked on the spot. Go to the first one

SQL subqueries are SELECT statements nested inside another statement, used as a single value, a list, or a temporary table. Interviewers use them to see whether you can filter on an aggregate or a related table without reaching for a join by reflex. Most questions turn on two things: the shape of what the subquery returns, and how NULL behaves when it is compared.

FormWhere it sitsWhat breaks or surprises
Scalar subquerySELECT list, or one side of a comparison in WHEREReturns more than one row and the engine raises an error.
IN subqueryWHERE col IN (SELECT ...)NOT IN returns no rows at all if the subquery produces a NULL.
EXISTS subqueryWHERE EXISTS (SELECT 1 ...)Stops at the first match, so the select list does not affect the result.
Correlated subqueryRefers to an alias from the outer queryLogically runs once per outer row; the optimizer may rewrite it as a join.
Derived tableFROM (SELECT ...) AS tMySQL requires the alias, and the outer query sees only the columns it returns.

Try these three exercises on a sample schema with customers and orders tables:

  1. Write "customers with no orders" three ways: NOT IN, NOT EXISTS, and LEFT JOIN with WHERE o.id IS NULL.
  2. Insert one order with a NULL customer_id and rerun all three. Only the NOT IN version changes, and it returns zero rows.
  3. Rewrite a correlated subquery that finds employees paid above their department average as a join against a grouped derived table, then compare the two EXPLAIN plans.

Key facts

  • Tarmac has 17 Databases & SQL interview questions on this topic, 10 of them on this page, at difficulty 1–5 of 5.
  • Tarmac tracked 3,405 job postings asking for Databases & SQL in November 2026.
  • Roles asking for Databases & SQL advertise a median base salary of £70,000, across 1,264 job postings as of November 2026.
  • Tarmac last reviewed these Databases & SQL interview questions on 3 December 2026.

At a glance

Questions10 shown · 17 in the bank
Difficulty1–5 of 5
FormatsMultiple choice, Flashcard, Multiple answer, Ordering, Coding exercise, Find the bug, True / false, Code output, Fill in the blank
Interactive1 run your code against tests, in the app

What you'll review

  1. subqueries
  2. window functions

Practice questions

Try one before you open the answer. Pick an option and press Check; it's marked on the spot.

In standard SQL, what does the following query return?#

Options

Show answer

A query with WHERE salary > (SELECT AVG(salary) FROM employees) returns the employees whose salary is above the company-wide average. The subquery returns a single value, the average salary. The outer query compares each row with that value and keeps only the rows that are higher.

Why:

The inner query SELECT AVG(salary) FROM employees is a scalar subquery that returns one value, the average salary. The outer query then compares each row's salary with that value and keeps only the rows where it is higher, so it returns the names of employees who earn more than the average. Subqueries are allowed in WHERE clauses, so the query does not raise an error. The query has no ORDER BY, so it doesn't sort anything, and it returns names rather than the average itself.

In SQL, what is a correlated subquery?#

Show answer

A correlated subquery is a subquery that references a column from the outer query. Because of that reference, it is logically evaluated once for each outer row. Example: SELECT name FROM employees e WHERE salary > (SELECT AVG(salary) FROM employees WHERE dept_id = e.dept_id); Here the inner query uses e.dept_id from the outer row.

Why:

A non-correlated subquery runs on its own, so it can be evaluated once. A correlated subquery depends on the outer row it is checking, so it is conceptually re-run for every outer row. Optimizers may still rewrite it as a join. It is a basic subquery term that interviewers often ask about.

In standard SQL (e.g., PostgreSQL), tables are customers(id, name) and orders(id, customer_id, amount). orders.customer_id contains no NULLs. Which of the following queries return exactly the customers who have placed at least one order, with each customer appearing once? Select all that apply.#

Options

Pick every one that applies.

Show answer

The correlated EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id) and id IN (SELECT customer_id FROM orders) both return each ordering customer exactly once, because they act as semi-joins. A plain JOIN repeats a customer once for each of their orders. An uncorrelated EXISTS is true for every customer whenever the orders table has any rows.

Why:

The correlated EXISTS subquery checks, per customer, whether any matching order exists, so each customer appears at most once. The IN (SELECT customer_id FROM orders) semi-join behaves the same way, and duplicates in the subquery do not duplicate outer rows. The plain JOIN returns one row per matching order, so a customer with three orders appears three times unless DISTINCT is added. The uncorrelated EXISTS (SELECT 1 FROM orders o) ignores the current customer: it is true for every customer as soon as the orders table has any row, so it returns all customers.

Arrange these clause fragments into one valid standard SQL query. The query lists each department whose average salary is above the company-wide average, highest average first. It uses a derived table (a subquery in FROM, with a correlation name) on employees(department, salary).#

Put these in order

Show answer

The standard SQL clause order is SELECT, then FROM, then WHERE, then ORDER BY. A query that lists departments above the company-wide average salary therefore reads its derived table in FROM before filtering with WHERE and sorting with ORDER BY, since each clause depends on the names produced by the one before it.

Why:

Standard SQL fixes the order of the main clauses: SELECT comes first, then FROM, then WHERE, then ORDER BY. Each fragment here is one whole clause, so the four pieces must appear in that sequence. The SELECT list names d.department and d.avg_sal, which only exist after the FROM clause defines the derived table d. The FROM fragment contains the complete inner query (grouping included) and ends with the required correlation name AS d, which standard SQL requires for a derived table. The WHERE clause filters on d.avg_sal against an uncorrelated scalar subquery over the whole table, and the ORDER BY sorts the surviving rows by average descending. Because every adjacent pair has a strict grammatical precedence, this is the only valid order.

The employees table has columns id (INTEGER), name (TEXT), and salary (INTEGER). Write a query returning the second-highest distinct salary as a single column named second_highest_salary (one row). Duplicate salaries count once — if two people share the top salary, the second-highest is the next distinct value down. If there is no second-highest distinct salary (every employee earns the same, or the table has fewer than two distinct salaries), return zero rows. Order by second_highest_salary descending so the result is deterministic.#

Starter code

-- Return: second_highest_salary (one row; zero rows if it does not exist)
SELECT

Your solution must pass

  • ties at the top still leave 75000 as second-highest

This one is written and run, not read. Solve it in the app and your code is executed against these tests and the hidden ones.

The author wants the top-earning employee per department. The query fails with an error. Which line is the bug?#

SELECT department, employee_name, salary
FROM employees
WHERE RANK() OVER (PARTITION BY department ORDER BY salary DESC) = 1;
Show answer

The bug is on line 3.

Why:

Window functions are evaluated after WHERE, so they cannot appear in a WHERE clause — the database raises an error (e.g. "window functions are not allowed in WHERE"). The fix is to wrap the window function in a CTE or subquery and filter in the outer query:

WITH ranked AS (
  SELECT department, employee_name, salary,
         RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk
  FROM employees
)
SELECT department, employee_name, salary
FROM ranked
WHERE rnk = 1;

In PostgreSQL, consider:#

Options

Show answer

In PostgreSQL, salary > ALL (empty subquery) evaluates to TRUE for every row, including rows where salary is NULL, so all rows are returned. An ALL condition over an empty set is vacuously true and no comparison is ever made. Rewriting it as salary > (SELECT MAX(salary) ...) returns no rows instead, because MAX of an empty set is NULL.

Why:

Under the SQL standard and in PostgreSQL, x > ALL (subquery) is true when the subquery returns no rows, because a universal condition over an empty set is vacuously true. The comparison operator is never evaluated, so even a NULL salary gives TRUE. The query therefore returns every row in employees. This often surprises people who expect > ALL to work like > (SELECT MAX(...)). That version returns no rows here, because MAX over an empty set is NULL and comparing with NULL gives UNKNOWN.

In modern PostgreSQL (12+), how does a non-recursive CTE (WITH x AS (...)) compare to writing the same query as an inline subquery?#

Options

Show answer

A non-recursive CTE and the equivalent inline subquery usually produce the same result and plan, so the CTE is mainly a readability and reuse aid. Since Postgres 12 the planner inlines non-recursive CTEs by default unless you write MATERIALIZED, so the CTE and the equivalent subquery typically optimize to the same plan. The CTE's value is clarity and being able to reference the named result more than once.

Why:

Since Postgres 12 the planner inlines non-recursive CTEs by default (unless you write MATERIALIZED), so a CTE and the equivalent subquery typically optimize to the same plan. The real value of a CTE is readability and being able to reference the named result more than once; recursion is a CTE-only feature (WITH RECURSIVE), which rules out the claim that subqueries can be recursive but CTEs cannot. Pre-12 Postgres did force materialization, which is the origin of the outdated 'CTEs are an optimization fence' belief.

customers(id) has ids 1, 2, 3. orders(customer_id) has rows for customer_id 1, 1, 3. What single number does this scalar query return?#

SELECT COUNT(*)
FROM customers c
WHERE EXISTS (
  SELECT 1 FROM orders o WHERE o.customer_id = c.id
);
Show answer
2
Why:

EXISTS is true for a customer as soon as the correlated subquery finds at least one matching order; it never multiplies rows. Customers 1 and 3 have orders, customer 2 does not, so exactly 2 rows satisfy the predicate and COUNT(*) returns 2.

In PostgreSQL (current versions), a subquery in the FROM clause normally cannot reference columns of other FROM items listed before it. To get a per-row top-3 such as SELECT c.id, o.* FROM customers c CROSS JOIN _____ (SELECT * FROM orders o WHERE o.customer_id = c.id ORDER BY amount DESC LIMIT 3) o;, you put the keyword _____ before the subquery. Separately, the planner can rewrite WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id) as a join. In EXPLAIN output this shows as a join node of the kind called a(n) _____ (for example, with a hash join strategy). The same rewrite is not done for NOT IN (subquery), because of how NOT IN handles NULLs.#

Show answer

In PostgreSQL (current versions), a subquery in the FROM clause normally cannot reference columns of other FROM items listed before it. To get a per-row top-3 such as SELECT c.id, o.* FROM customers c CROSS JOIN **LATERAL** (SELECT * FROM orders o WHERE o.customer_id = c.id ORDER BY amount DESC LIMIT 3) o;, you put the keyword LATERAL before the subquery. Separately, the planner can rewrite WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id) as a join. In EXPLAIN output this shows as a join node of the kind called a(n) anti join (for example, with a hash join strategy). The same rewrite is not done for NOT IN (subquery), because of how NOT IN handles NULLs.

Why:

LATERAL lets a FROM-clause subquery (or a function call) refer to columns of FROM items that come before it. The subquery then runs once per outer row, which is the standard way to do a per-group top-N. PostgreSQL turns a correlated NOT EXISTS into an Anti Join node (Hash Anti Join, Merge Anti Join or Nested Loop Anti Join). An anti join returns the outer rows that have no match. NOT IN cannot be turned into an anti join, because one NULL in the subquery's results makes the predicate UNKNOWN instead of TRUE, and anti-join semantics don't match that. So NOT IN is run as a SubPlan or hashed SubPlan instead.

Sources

The official documentation these questions are checked against:

Related interview questions

Job market

See databases-sql salaries and hiring demand from live job postings.

The other 7 questions

This page shows 10 and marks what you pick. That's as far as a page can go. A free account opens the other 7 and keeps every answer. What you miss comes back until it's right: after a day, then at longer gaps.

Start with this topic

Free · the whole bank · 100 answers per 30 days, each marked with written feedback

Interview booked? Practise the job ad instead

What moved, monthly

One email a month when the bulletin comes out: what moved in the markets we track, and the new question topics we published. Confirm your address to join. Unsubscribe any time.