Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 62/ 160
04. Subqueries & Common Table Expressions (CTEs)

Column & Row Subqueries (IN, ANY, SOME, ALL)

Compare against sets of values using IN, ANY, SOME, and ALL.

IntermediateIN · ANY / SOME3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

IN asks "is it in the list?", ANY asks "does it beat at least one?", and ALL asks "does it beat every one?".

Think of it like…

Comparing a runner with a team: "faster than ALL of them" means beating the fastest; "faster than ANY of them" means beating at least the slowest.

Where you’ve seen it

Employees paid more than everyone in the Support team: SELECT name FROM employees WHERE salary > ALL (SELECT salary FROM employees WHERE dept = 'Support'); and orders matching a list of (customer, product) pairs: WHERE (customer_id, product_id) IN (SELECT customer_id, product_id FROM promo_targets).

Words you’ll hear

IN / = ANY
True if the value equals at least one value from the subquery.
> ANY
Greater than at least one value (equivalent to > MIN in the usual case).
> ALL
Greater than every value (equivalent to > MAX in the usual case).
Row constructor
(a, b) compared with a subquery returning two columns.

Visual diagram

Loading interactive diagram

Theory & example queries

IN, ANY and ALL

x IN (subquery) and x = ANY (subquery) mean the same thing. With other operators, ANY and ALL compare against every returned value: x > ANY (…) is true if x beats at least one value, and x > ALL (…) only if it beats them all. In the normal case they match x > (SELECT MIN(…)) and x > (SELECT MAX(…)), which some people find clearer.

Edge cases differ from the MIN/MAX versions. Over an empty subquery, ALL is true (every one of zero values is beaten) and ANY is false, while comparing with MAX of nothing gives NULL, so no rows. If the subquery contains a NULL, x > ALL (…) can never be TRUE, because the comparison with NULL is UNKNOWN; NOT IN has the same problem.

Empty and NULL behaviourQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  10 > ALL (3    SELECT4      15    WHERE6      FALSE7  )
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/7
query.sql
1SELECT2  10 > ALL (3    VALUES4      (5),5      (NULL)6  )
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/6
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output2 sample rows
Expected output
inputresult
empty ALL settrue
values 5 and NULLNULL

Note: Combines the two scalar SELECT results for clarity; the NULL comparison is filtered out in a WHERE clause.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

returns true;

returns NULL, so a WHERE with it keeps nothing.

Key takeaway: ANY = at least one, ALL = every one; watch empty sets and NULLs.

Row subqueries

Several columns can be compared together: (customer_id, product_id) IN (SELECT customer_id, product_id FROM promo_targets) matches only exact pairs, which isn't the same as checking each column separately. A scalar row comparison like (a, b) = (SELECT x, y FROM … LIMIT 1) must return exactly one row.

Row comparisons with < and > work lexicographically: (created_at, id) < ($1, $2) compares created_at first and id only on ties, which is exactly what keyset pagination needs. PostgreSQL and MySQL support row constructors; SQL Server doesn't, so use EXISTS with two conditions there.

Exact pair matching with EXISTS (portable)Query example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  o.*3FROM4  orders o5WHERE6  EXISTS (7    SELECT8      19    FROM10      promo_targets t11    WHERE12      t.customer_id = o.customer_id13      AND t.product_id = o.product_id14  );
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/14
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
idcustomer_idproduct_idamount
5014211750
5174224120
5307711980

Note: Illustrative matching orders; the result's other o.* columns are omitted from this display.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Tuples compare as a whole; EXISTS is the portable alternative.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Requirement

Phrase the comparison

Decide whether the value must match one, beat at least one, or beat every value in the set.

Focus at this step

in the set · beats any · beats all

What to watch at this step
Pick
IN / ANY / ALL
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A column subquery returns one column of many rows, used with IN, ANY (or SOME) and ALL: price > ALL (SELECT price FROM …) means greater than every value, > ANY means greater than at least one, and = ANY is the same as IN. A row subquery returns several columns, compared as a tuple: (customer_id, product_id) IN (SELECT …).

Why it matters: These operators answer comparative questions directly: "products more expensive than everything in the budget range", "employees earning more than anyone in sales". They also have sharp edges with empty results and NULLs (ALL over an empty set is true; one NULL can make ALL return nothing), which interviewers enjoy testing.

When to reach for it

  • Comparisons against every or any value in a group
  • Matching exact pairs of values
  • Keyset pagination with row comparisons

When to avoid or be careful

  • ALL against subqueries that can contain NULLs
  • Assuming > ALL of an empty set excludes rows
  • Checking pairs with two separate IN conditions

ALL / ANY vs MAX / MIN vs EXISTS

> ALL / > ANY
Best for: Directly expressing "beats every" or "beats at least one"

Strengths: Reads like the question.

Watch out: Surprising results with empty sets and NULLs.

> (SELECT MAX / MIN …)
Best for: The same comparisons with clearer intent

Strengths: Familiar; NULLs ignored by MAX/MIN.

Watch out: Empty set gives NULL, which keeps no rows.

EXISTS / NOT EXISTS
Best for: Multi-column matches and anti-joins

Strengths: NULL-safe and portable.

Watch out: More verbose for simple comparisons.

Interview signals & numbers to know

When this topic comes up

  • “Earn more than everyone in department X”
  • “ANY vs ALL”
  • Matching pairs of values
  • NOT IN returning nothing
  • Row value comparisons

Benchmarks & rules of thumb

= ANY -
same as IN
> ALL (empty) -
TRUE
> ANY (empty) -
FALSE

Common mistakes & follow-ups

Common interview mistakes

  • Writing customer_id IN (…) AND product_id IN (…) and matching combinations that aren't real pairs.
  • Expecting salary > ALL (…) to work when one salary in the subquery is NULL.
  • Forgetting that > ALL over an empty department returns every employee.

Likely interviewer follow-ups

  • What's the difference between > ANY and > ALL?
  • What does x > ALL return when the subquery returns no rows?
  • How would you match exact (customer, product) pairs in SQL Server?
Interview tip: Explain ANY and ALL with one three-value list, then mention the empty-set and NULL cases. Those edge cases are the real test.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Column & Row Subqueries (IN, ANY, SOME, ALL) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Scalar Subqueries (Single Value in SELECT or WHERE)
Next topic
Subqueries in the FROM Clause (Derived Tables)