Semi-Joins and Anti-Joins

High-value EXISTS, IN, NOT EXISTS, and LEFT JOIN IS NULL patterns for membership and missing-row queries.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

Semi-joins

Return left-side rows when a related match exists.

Use EXISTS for semi-join behavior

Return customers who have at least one order without duplicating customer rows.

sqlANYexistssemi-join
sql
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (
  SELECT 1
  FROM orders o
  WHERE o.customer_id = c.customer_id
);
Notes

`EXISTS` is often clearer and more efficient than joining and deduplicating.

Use IN for simple membership checks

Another semi-join style when selecting from a single column set.

sqlANYinsemi-join
sql
SELECT customer_id, name
FROM customers
WHERE customer_id IN (
  SELECT customer_id
  FROM orders
);
Notes

`IN` can be concise, but `EXISTS` is often preferred for correlated logic and large subqueries.

Anti-joins

Return left-side rows with no related match.

Use NOT EXISTS for anti-join behavior

Find customers who have never ordered.

sqlANYnot-existsanti-join
sql
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (
  SELECT 1
  FROM orders o
  WHERE o.customer_id = c.customer_id
);
Notes

`NOT EXISTS` is usually the safest anti-join pattern.

LEFT JOIN ... IS NULL anti-join

Find unmatched rows by outer join plus null check.

sqlANYleft-joinanti-join
sql
SELECT c.customer_id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.customer_id IS NULL;
Notes

Common and readable, though `NOT EXISTS` is often more robust when multiple conditions are involved.

Be careful with NOT IN and NULLs

A single `NULL` in the subquery can change results in surprising ways.

sqlANYnot-innulls
sql
Prefer:
WHERE NOT EXISTS (...)

Use caution:
WHERE id NOT IN (SELECT some_nullable_column FROM t)
Notes

`NOT IN` can yield no rows if the subquery returns `NULL`. `NOT EXISTS` avoids that pitfall.

Recommended next

No recommendations yet.