This is one of the most tricky SQL interview questions.
#sql #databases #backendengineering
This is one of the most tricky SQL interview questions.
IN vs EXISTS — when should you use which?
1️⃣ IN — when the result set is small
IN works best when the subquery returns a small list of values.
Simple and readable, but risky with NULLs.
SELECT * FROM orders
WHERE customer_id IN (SELECT id FROM customers);
2️⃣ EXISTS — when checking existence
EXISTS stops as soon as it finds a match.
Better for large tables and correlated subqueries.
SELECT * FROM orders o
WHERE EXISTS (
SELECT 1 FROM customers c
WHERE c.id = o.customer_id
);
3️⃣ NULL trap
IN fails if the subquery returns NULL.
EXISTS handles NULL safely.
4️⃣ Performance difference
IN compares full result sets.
EXISTS checks row-by-row and can exit early.
5️⃣ Interview rule of thumb
Use IN for small, clean datasets.
Use EXISTS for large tables and NULL-safe logic.
{ SQL, Databases, BackendEngineering, InterviewPrep, QueryOptimization, TechExplained }
#SQL
#Databases
#BackendEngineering
#InterviewPreparation
#TechExplained
Comments
Comments from the original post on Instagram
No comments yet
