sql / intermediate
Snippet
Optimizing Subquery Filtering using the EXISTS Operator
The EXISTS operator performs short-circuit evaluation, returning TRUE as soon as the query engine finds a single matching record in the subquery. This is significantly more efficient for large datasets compared to using IN with subqueries.
snippet.sql
sql
1
2
3
4
5
6
7
8
9
10
SELECTc.customer_id,c.company_nameFROM customers cWHERE EXISTS (SELECT 1FROM orders oWHERE o.customer_id = c.customer_idAND o.order_status = 'COMPLETED');
Breakdown
1
FROM customers c
Assigns an alias to the outer table to enable correlation within the subquery.
2
WHERE EXISTS (
Evaluates truthiness based on early matching without building full result sets.
3
SELECT 1
Returns a constant scalar value since EXISTS only checks row existence, not actual column values.
4
WHERE o.customer_id = c.customer_id
Correlates each outer customer row with matching order records.