Summary
Full Transcript
Follow @RebellionRider for more SQL interview questions. Interviewer: Why does using OR in WHERE slow down SQL compared to UNION ALL? Here’s the blunt truth. OR confuses the optimizer. When you write: WHERE col1 = 10 OR col2 = 20 The database often cannot use indexes efficiently. It may ignore both indexes. It may switch to a full table scan. Because it has to evaluate multiple conditions per row and combine them. Now look at UNION ALL. You split the logic into two clean queries. Each query can use its own index. Each query can get its own optimal execution plan. Then the results are simply appended together. No deduplication. No extra sorting. No unnecessary merging logic. OR creates a messy execution path. UNION ALL creates two clean ones. And databases love clean paths. Is OR always bad? No. But on large tables with proper indexes, it can silently kill performance. Average candidates write working queries. Strong candidates think about execution plans.
