Skip to content

Rows with no match

Find customers with no orders, products never sold and other missing rows, and avoid the NOT IN NULL trap.

Practise: 9 questions

When you need it

"Customers who never ordered", "products with no sales", "accounts with no invoice this year", "tickets nobody answered". Words that signal it: "never", "no", "without", "not in", "haven't", "missing", "didn't".

You are looking for rows in table A that have no partner in table B. The answer is a list of A rows, not a combination of A and B.

The shape of the query

Three forms give the same answer when written correctly.

-- 1. NOT EXISTS
select a.* from a
where not exists (select 1 from b where b.a_id = a.id);

-- 2. LEFT JOIN with an IS NULL test
select a.* from a
left join b on b.a_id = a.id
where b.a_id is null;

-- 3. NOT IN (risky)
select a.* from a
where a.id not in (select a_id from b);

Step by step:

  1. Decide which table lists the things you want to find (the A side).
  2. Decide what counts as a match. "Never ordered" might mean no order at all, or no completed order. Put that condition inside the subquery or the ON clause.
  3. Keep A rows where no match exists.
select c.customer_id, c.full_name
from customers c
where not exists (
  select 1
  from orders o
  where o.customer_id = c.customer_id
    and o.status = 'completed'
)
order by c.customer_id
limit 10;

The same question with a left join:

select p.product_id, p.product_name
from products p
left join order_items oi on oi.product_id = p.product_id
where oi.product_id is null
order by p.product_id;

Test for NULL on a column that cannot be NULL in a real match, such as the join key from the right table. Testing a column that can be NULL itself gives false positives.

Traps interviewers look for

Variations

In other warehouses

Practise rows with no match