✏️ Explanatory Question

What is the difference between IN and EXISTS?

👁 13 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

45

What is the difference between IN and EXISTS?

Level: Intermediate to Advanced — A frequent question testing subquery performance intuition.

Both IN and EXISTS are used with subqueries to filter rows, but they work differently under the hood:

  • IN: Compares a value against a list of values returned by the subquery. The subquery runs first and builds the full list.
  • EXISTS: Checks whether the subquery returns any rows at all (true/false). It stops at the first match — it doesn't build a list.
Rule of thumb: Use IN when the subquery returns a small list. Use EXISTS when the subquery is large or correlated, since it short-circuits on the first match.

Side-by-Side Comparison

Feature IN EXISTS
Checks Value in a list Whether rows exist
Subquery execution Builds full result list Stops at first match
Best for Small subquery results Large / correlated subqueries
NULL handling Can behave unexpectedly with NULLs Not affected by NULLs
Returns Matches from the list Boolean (true/false)

The NULL Gotcha with IN

If the subquery used by IN returns a NULL, a NOT IN comparison can unexpectedly return no rows at all, because comparing anything to NULL yields "unknown". EXISTS / NOT EXISTS does not suffer from this issue.

Quick Example

-- IN: employees in Kolkata-based departments (small list)
SELECT name FROM employees
WHERE dept_id IN (
    SELECT dept_id FROM departments WHERE location = 'Kolkata'
);

-- EXISTS: departments that have at least one employee (correlated)
SELECT d.dept_name FROM departments d
WHERE EXISTS (
    SELECT 1 FROM employees e WHERE e.dept_id = d.dept_id
);

-- NOT EXISTS: departments with NO employees (safe with NULLs)
SELECT d.dept_name FROM departments d
WHERE NOT EXISTS (
    SELECT 1 FROM employees e WHERE e.dept_id = d.dept_id
);

-- NOT IN NULL trap: if the subquery returns a NULL, this may return nothing!
-- SELECT name FROM employees
-- WHERE dept_id NOT IN (SELECT dept_id FROM departments);
Interviewer tip: The one-liner they want — "IN compares a value against a list from the subquery, while EXISTS just checks whether the subquery returns any rows and stops at the first match. EXISTS is often faster for large or correlated subqueries and is NULL-safe."