Subqueries, EXISTS & set operations
A subquery is a query embedded inside another SQL statement. Set operations combine complete query results. These tools are especially useful when the business rule is naturally phrased as “rows where another set contains/does not contain something.”
Scalar subqueries
A scalar subquery must return one value. It can be compared with each outer row.
Run the query to see the result.
If the subquery unexpectedly returns multiple rows, engines normally raise an error rather than guessing.
IN with a subquery
Run the query to see the result.
IN is readable when NULL behavior is understood and the intent is membership in a set.
EXISTS and correlated subqueries
EXISTS asks whether at least one row satisfies a condition. The subquery can refer to the current outer row.
Run the query to see the result.
SELECT 1 is conventional because EXISTS cares about row existence, not selected values.
NOT EXISTS for missing relationships
Run the query to see the result.
This avoids the NULL trap associated with NOT IN.
UNION versus UNION ALL
UNION combines result sets and removes duplicates. UNION ALL preserves every row and is normally faster because it does not need duplicate elimination.
Run the query to see the result.
Choose UNION only when deduplication is actually part of the requirement.
INTERSECT and EXCEPT
INTERSECT returns rows present in both result sets. EXCEPT returns rows from the first set that are absent from the second. They are excellent for expected-versus-actual comparisons when both sides have compatible columns.
Run the query to see the result.
Reverse the two sides to find unexpected actual rows.
When to prefer joins, EXISTS, or sets
Use a join when you need columns from both relations. Use EXISTS when you only need to test presence. Use a set operation when you are comparing entire compatible row sets. These choices often express intent better than forcing every problem into a join.
Practice: return customers that have a paid order but no pending order.