Understanding EXISTS in SQL The EXISTS keyword in SQL evaluates to TRUE under which circumstance?

Difficulty: Easy

Correct Answer: When any row in the subquery meets the condition only.

Explanation:


Introduction / Context:
EXISTS and NOT EXISTS are fundamental to writing presence/absence logic in SQL, especially for correlated subqueries. They check for the existence of qualifying rows rather than specific values, which makes them robust in the presence of NULLs.



Given Data / Assumptions:

  • We are using a subquery that may return zero or more rows.
  • EXISTS evaluates to a Boolean based solely on row presence.
  • The subquery is often correlated to the outer row.


Concept / Approach:

EXISTS returns TRUE as soon as the subquery finds a single row satisfying the condition. The values returned by the subquery do not matter; even SELECT 1 works because only existence matters. If no qualifying row is found, EXISTS returns FALSE.



Step-by-Step Solution:

Write: WHERE EXISTS (SELECT 1 FROM Child c WHERE c.parent_id = p.id).If at least one Child row exists for the current Parent, the condition is TRUE.If none exist, the condition is FALSE.Short-circuit behavior means evaluation stops on the first match.


Verification / Alternative check:

Compare with IN; EXISTS vs IN can be equivalent, but EXISTS is safer with NULLs. Query plans commonly show semi-joins for EXISTS predicates.



Why Other Options Are Wrong:

  • B: Describes NOT EXISTS, not EXISTS.
  • C/D: Mutually incompatible and not how EXISTS works.
  • E: NULLs do not matter; only the presence of a row matters.


Common Pitfalls:

  • Expecting EXISTS to count rows; it does not—it is a Boolean test.
  • Returning actual columns in the EXISTS subquery unnecessarily; SELECT 1 is sufficient.


Final Answer:

When any row in the subquery meets the condition only.

More Questions from Database Redesign

Discussion & Comments

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