SQL Trap: IN vs EXISTS with NULLs

⚠️ DAY 9/15 — SQL TRAP: IN vs EXISTS Your query returns 0 rows. No error. No warning. One NULL in the list is silently killing all your results. 👇 🎯 The Situation: You want to find all employees whose department exists in the departments table. You use IN. Looks perfect. Runs fine. Result → 0 rows. 😵 But the departments ARE there! Alice, Bob, Dave all have valid departments! What just happened? 🧠 Here's the silent killer: Look at the departments table. One row has DEPT_ID = NULL for HR. When IN sees that NULL in the list — it compares every employee's dept_id against it. NULL comparison = UNKNOWN. Always. Now SQL is unsure about EVERY row. So it returns NOTHING. Zero rows. Silently. 😬 One NULL in the subquery. Entire result — wiped out. ✅ The Fix — Use EXISTS instead: EXISTS doesn't compare values in a list. It simply asks row by row — "Does a matching row exist? Yes or No?" NULLs in the subquery? EXISTS doesn't care. It just checks for a match and moves on. Result → Alice, Bob, Dave returned correctly ✅ 💡 Real Life Example: IN = checking if your name is on a guest list If the list has one smudged unreadable name — IN panics and says "I can't confirm ANYONE" ❌ EXISTS = a security guard checking each person one by one One smudged entry doesn't stop everyone else from entering ✅ 📌 Save This Rule: → Using IN with a subquery? → Check if NULLs can exist in that list → Subquery might return NULLs? → Always use EXISTS instead → IN works fine with fixed value lists like IN (10, 20, 30) → EXISTS is always NULL-safe for subqueries → When in doubt → EXISTS is the safer choice 🔑 One Line to Remember: IN + NULL in list = 0 rows silently EXISTS + NULL = works perfectly fine Same goal. Very different behaviour with NULLs. Follow for Day 10 tomorrow 🚀 #SQL #SQLForBeginners #DataAnalytics #LearnSQL #SQLTips #DataEngineering #InterviewPrep

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories