Difficulty: Easy
Correct Answer: NOT EXISTS
Explanation:
Introduction / Context:It is common to ask for rows that do not have a related record, such as customers without orders or products without prices. SQL provides several ways to express anti-matching; choosing the right one affects both correctness and performance.
Given Data / Assumptions:
Concept / Approach:
NOT EXISTS expresses anti-matching cleanly: it is TRUE when the subquery returns no rows meeting the specified condition. Because EXISTS/NOT EXISTS respond only to row presence (not values), they avoid pitfalls where NULLs in subquery results can cause unexpected filtering (common with NOT IN).
Step-by-Step Solution:
Frame a correlated subquery: SELECT * FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id).The subquery searches for any related orders for the current customer.If none are found, NOT EXISTS evaluates to TRUE and the customer is returned.If at least one exists, NOT EXISTS is FALSE and the row is excluded.Verification / Alternative check:
Replace NOT EXISTS with LEFT JOIN ... WHERE o.customer_id IS NULL as an equivalent anti-join; both convey the same intent when written correctly and with appropriate NULL handling.
Why Other Options Are Wrong:
Common Pitfalls:
Final Answer:
NOT EXISTS
Discussion & Comments