17. Correlated Subqueries & EXISTS
Core Idea: A correlated subquery depends on values from the current candidate row of the outer query. It evaluates repeatedly for every row processed by the parent query.
The EXISTS Operator
EXISTS returns true as soon as the subquery finds at least one matching row, stopping further scanning immediately (short-circuit boolean check).
NOT EXISTS vs NOT IN
NOT EXISTS safely handles nulls, unlike NOT IN which can fail to return results if the subquery produces even a single NULL value.
Correlated Comparison Queries
Advanced Deep Dive ADVANCED
SELECT 1 in EXISTS: Conventionally SELECT 1 or SELECT * is used in EXISTS because the optimizer only tests for the existence of rows without retrieving column data.
The NOT IN / NULL Trap: If any row returned by a subquery is NULL, column NOT IN (subquery) evaluates to UNKNOWN and yields zero rows! Always prefer NOT EXISTS for anti-semi-joins.
Semi-Join Transformation: The SQL Server Query Optimizer converts EXISTS queries into Semi-Join or Anti-Semi-Join plan operators for optimal performance.