Finding rows that do NOT meet a specified condition In standard SQL, which construct is most appropriate to return rows that have no matching rows satisfying a condition in a related set?

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:

  • A main table (outer query) and a related table (inner subquery) exist.
  • We want rows where no qualifying related rows exist.
  • NULL semantics can affect IN/NOT IN behavior.


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:

  • A: EXISTS returns rows when a match does exist, not when it does not.
  • B: Doubling NOT EXISTS is unnecessary and creates confusion.
  • D/E: Incorrect or error-prone approaches, especially with NULLs in IN lists.


Common Pitfalls:

  • Using NOT IN with a subquery that returns NULLs, which can exclude all rows.
  • Forgetting correlation, leading to global NOT EXISTS that returns unintended results.


Final Answer:

NOT EXISTS

More Questions from Database Redesign

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion