Question presented to candidate:
"Say I want every customer who has placed at least one order. I could write WHERE id IN (SELECT customer_id FROM orders) or WHERE EXISTS (SELECT 1 FROM orders WHERE ...). What is the difference between the two, do they return the same rows, and which one would you pick?"
What a strong answer should cover:
INtests whether a value is a member of a list or of one column returned by a subquery;EXISTStests whether a (usually correlated) subquery returns at least one row- Both are semi joins: each outer row comes back at most once, however many matches there are
EXISTSignores the select list (SELECT 1,SELECT *, evenSELECT 1/0all behave the same) and can carry any multi-column or non-equality condition- For positive checks they return the same rows even with NULLs; the real difference shows up with
NOT INversusNOT EXISTS - Performance: modern optimizers (PostgreSQL, MySQL 8.0.16+) usually plan both the same way; older advice "EXISTS is always faster" is engine- and version-specific, so read the plan
Code / implementation expected: Yes β the same "customers with an order" query written with IN and with EXISTS, plus one check that needs more than one column.
Schema used by the examples: