QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › Subqueries, CTEs, set operations

How does IN differ from EXISTS?

IN looks for a value in a subquery's list, while EXISTS checks whether the subquery returns any row for the current row. Unlike a JOIN, neither duplicates rows. In the positive form the planner usually builds the same semi-join, so EXPLAIN decides. The real difference is negation: NOT IN breaks on a NULL in the subquery, NOT EXISTS does not.

SQL · Subqueries, CTE, sets

A query for "users with a failed transaction" returns Anna twice. How to keep one row each?

A QA engineer looks for users who had at least one failed transaction. A query with JOIN returns Anna twice because she has two failed ones. Someone adds DISTINCT, someone writes IN, someone EXISTS. All three give an answer, but they behave differently with duplicates, with NULL and on big data. This lesson covers what exactly IN and EXISTS compare and when the choice matters.

How it works and why. IN takes the value on the left and looks for it in the list the subquery returns: "is this id among these user_ids?". EXISTS compares nothing with a list: it runs the subquery for the current row and asks whether there is at least one row: "is there a failed transaction of exactly this user?". So in EXISTS the subquery is almost always correlated and its columns do not matter, people write SELECT 1. The outer row is taken once, no duplicates appear and execution may stop at the first match.

-- users with at least one failed transaction: anna
SELECT u.email
FROM users u
WHERE u.id IN (
  SELECT a.user_id
  FROM accounts a
  JOIN transactions t ON t.account_id = a.id
  WHERE t.status = 'failed'
);

SELECT u.email
FROM users u
WHERE EXISTS (
  SELECT 1
  FROM accounts a
  JOIN transactions t ON t.account_id = a.id
  WHERE a.user_id = u.id AND t.status = 'failed'
);

On the sample data (failed transaction 3 belongs to account 11 of user 1) both queries return Anna once. For positive IN and EXISTS the PostgreSQL planner usually builds the same plan (a semi-join), so speed makes no difference. The difference shows up in two places.

What each of the two does

IN

Compares with a list

The subquery returns a list of values and the outer value is looked up in it. A NULL in the list never matches.

EXISTS

Asks about presence

For each row it checks whether the subquery has at least one row. NULL does not affect the result.

Figure 1. Both fit a semi-join: an outer row is taken once.

First place: duplicates compared with JOIN. If the same requirement were written with JOIN, a user with two failed transactions would appear twice. IN and EXISTS do not do that because they only filter rows and never multiply them:

-- a JOIN duplicates the user when there are several failures
SELECT u.email
FROM users u
JOIN accounts a ON a.user_id = u.id
JOIN transactions t ON t.account_id = a.id
WHERE t.status = 'failed';
-- with two failures for anna: two rows of anna

Second place: negation. NOT IN and NOT EXISTS are not equivalent. If the subquery has even one NULL, NOT IN returns an empty result while NOT EXISTS works correctly. This is a separate lesson, and it is the main reason to prefer EXISTS in negations.

Limits and alternatives. If you need columns from the subquery (the sum of failures, the date of the last one), EXISTS does not fit because it returns only true or false. Then use a JOIN with an aggregate or a window function. IN is handy with a short explicit list (status IN ('failed', 'cancelled')). EXISTS is handy when the condition depends on several columns of the outer row. Old rules such as "EXISTS is always faster" or "IN is always slower" are outdated: decide by EXPLAIN on a realistic volume.

Typical mistakes.

  • JOIN instead of EXISTS where only the fact is needed: duplicates and inflated counts.
  • In an EXISTS subquery the link to the outer row is forgotten (a.user_id = u.id): the condition becomes independent and the query returns either everyone or nobody.
  • SELECT * in EXISTS is believed to be slow. That is a myth: the columns are not evaluated, but SELECT 1 reads clearer.
  • NOT IN over a column that may hold NULL: an empty result with no error.

Check yourself

A user has two failed transactions. How many rows of this user do the IN, EXISTS and JOIN queries return?

Answer

IN and EXISTS return one row: they only check presence. JOIN returns two, one per failed transaction. If you need a list of users rather than transactions, JOIN needs DISTINCT and EXISTS does not.

When do you need a JOIN instead of EXISTS?

Answer

When you need values from the second table: the sum of failures, the date of the last one. EXISTS returns only yes or no, you never see the rows of the subquery.

In an interview. Junior: IN compares a value with a list from the subquery, and EXISTS only checks whether at least one row exists. For "has at least one such record" I take EXISTS because a JOIN would give duplicates. Middle/Senior: In the positive form the planner usually builds the same semi-join, so speed is not an argument and I decide by EXPLAIN. The difference is fundamental in negation: NOT IN breaks on a NULL in the subquery and NOT EXISTS does not. If I need values from the second table, EXISTS does not fit and I take a JOIN with an aggregate.

More articles in this chapter