Repaso
EspaƱol
Databases & SQLIntermediateDB-44

Which query lists customers who have NO orders?

Options

  1. SELECT * FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id) (Correct option)
  2. SELECT * FROM customers c WHERE c.orders = 0 OR c.orders IS NULL OR c.order_count < 1
  3. SELECT * FROM customers c INNER JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL
  4. SELECT c.* FROM customers c WHERE c.id NOT IN (SELECT o.id FROM orders o) AND c.active

Answer

SELECT * FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)

Why

NOT EXISTS with a correlated subquery checks, for each customer, whether any order row points to them. If none, the customer is returned.

Equivalent: LEFT JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL (anti-join).

Be careful with NOT IN (subquery): if the subquery returns any NULL, the result becomes empty. NOT EXISTS avoids this problem.

SELECT c.*
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;

Remember

Customers without orders: LEFT JOIN ... IS NULL, or NOT EXISTS.

Key terms

Practice this question in Repaso