Difficulty: Medium
Correct Answer: Correct
Explanation:
Introduction / Context:
NOT EXISTS is widely used for anti-joins: returning rows from one set that do not have matching rows in another. A double NOT EXISTS pattern is also common in relational division problems (e.g., find customers who bought all items in a set). Understanding these constructs is critical for writing expressive, performant SQL without resorting to procedural loops.
Given Data / Assumptions:
Concept / Approach:
Single NOT EXISTS implements anti-join: return parent rows for which no child row satisfies the condition. Double NOT EXISTS implements “not exists a required element that is not matched,” which is equivalent to “for all required elements, at least one match exists.” This pattern elegantly encodes universal quantification in SQL.
Step-by-Step Solution:
For anti-join: SELECT p.* FROM P p WHERE NOT EXISTS (SELECT 1 FROM C c WHERE c.key = p.key).For division: SELECT p.* FROM P p WHERE NOT EXISTS (SELECT 1 FROM R r WHERE NOT EXISTS (SELECT 1 FROM C c WHERE c.pkey = p.key AND c.attr = r.attr)).Ensure indexes on keys used in correlated predicates.Validate correctness with controlled test data.Compare to LEFT JOIN ... WHERE child.key IS NULL for anti-joins.
Verification / Alternative check:
Construct small sets where expected results are obvious; confirm that NOT EXISTS and double NOT EXISTS return exactly those rows.
Why Other Options Are Wrong:
NULLs in unrelated columns do not invalidate NOT EXISTS logic; modern SQL fully supports these constructs.
Common Pitfalls:
Forgetting to correlate correctly; missing indexes; misapplying NOT IN with NULLs, which behaves differently.
Final Answer:
Correct
Discussion & Comments