In database interviews, one classic question that frequently trips up even seasoned developers is: "Between EXISTS and IN, which query is faster?" The answer isn't always straightforward—it depends on the relative sizes of the outer and inner tables and how the SQL query optimizer handles the query.
Key Factors Affecting Speed
-
Table Size Ratio: If the outer table is large and the inner table is small,
INcan be faster because it builds a temporary list of values from the inner query. Conversely, when the outer table is small and the inner table is large,EXISTSoften wins because it uses short-circuit evaluation—it stops scanning the inner table as soon as a match is found. -
Query Optimizer Behavior: Modern optimizers (in MySQL, PostgreSQL, Oracle, etc.) may perform subquery flattening, rewriting
INasEXISTSor vice versa, sometimes making them equivalent. However, the optimizer's cost-based decisions can still lead to performance differences in practice. -
Memory vs Short-Circuit:
INbuilds a temporary result set (using memory), whileEXISTSdoes row-by-row checks with early termination. This can drastically affect speed for large datasets.
Practical Takeaways for Interviews
- For senior backend, data engineer, or DBA roles, show you understand that there is no universal answer. Always analyze table sizes and execution plans.
- Use
EXPLAIN(orEXPLAIN ANALYZE) to see which plan the optimizer chooses. - In modern databases, the performance gap is narrowing, but knowing the theory still matters.
Follow for More
Stay tuned for more SQL optimization tricks, query execution plan hacks, and interview-ready insights from the Database AI Classroom series.