SpinTheMic
Pro

SQL · Intermediate

What is the difference between EXISTS, IN and NOT IN?

By Anurag Pandey, Lead Data Engineer ·

The short answer

IN checks a value against a list or subquery; EXISTS checks whether a subquery returns any row. Their results usually match. NOT IN is the trap: if the subquery returns a NULL, NOT IN returns no rows, so NOT EXISTS is the safer choice.

Practice this out loud

Opens this question on SpinTheMic. Start without signing up; sign in free for an AI report card.

Say it like this

About 55 seconds out loud. Use it as a model, then put it in your own words.

IN checks if a value matches anything in a list or a subquery, like customer_id IN select customer_id from orders. EXISTS checks if a correlated subquery returns at least one row, and it can stop as soon as it finds one. For finding matches, the two usually give the same result, and modern optimizers often run them the same way. The important difference is with negation. NOT IN behaves badly with NULLs. If the subquery returns even one NULL, then 'value NOT IN the list' can never be true, because comparing with NULL gives unknown. So the query returns no rows at all. NOT EXISTS doesn't have this problem, because it only asks whether a matching row exists. That's why I use NOT EXISTS, or a left join with an IS NULL check, for anti-joins.

What interviewers look for

  • You explain how IN and EXISTS each decide a match.
  • You know the NOT IN and NULL trap and why it happens.
  • You suggest NOT EXISTS or a left anti-join as the safe pattern.

Common mistakes

  • Saying EXISTS is always faster than IN. Optimizers often treat them the same.
  • Not knowing what NOT IN does when the subquery contains a NULL.
  • Writing NOT IN on a nullable column in production code.

Follow-up questions to expect

  1. 1Write a query that finds customers with no orders.
  2. 2Why does comparing with NULL give unknown instead of false?
  3. 3What is a semi-join and an anti-join?
Practice this out loud

Opens this question on SpinTheMic. Start without signing up; sign in free for an AI report card.

Checked against

All interview question guides