capypad
0 day streak
sql / expert
Snippet

Correlated Subqueries for Anti-Joins

A correlated subquery references columns from the outer query. Using NOT EXISTS with a correlated subquery is a highly performant way to implement anti-joins, such as finding customers who haven't placed an order in the last year.

snippet.sql
sql
1
2
3
4
5
6
7
8
SELECT c.customer_name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
AND o.order_date > CURRENT_DATE - INTERVAL '365' DAY
);
Breakdown
1
WHERE NOT EXISTS (
Filters for rows where the subquery returns no results.
2
SELECT 1 FROM orders o
The subquery selects a constant to minimize overhead since only existence matters.
3
WHERE o.customer_id = c.id
The correlation: links the subquery record to the current outer row.