Video in progress

How do you write the condition "does the customer have at least one paid order?", and why is `COUNT(*) > 0` worse?

EXISTS (SELECT 1 FROM orders WHERE ...) stops as soon as it finds the first matching row. COUNT(*) > 0 counts all the matching rows, even though all we need is "yes or no".

📖 Answer

-- bad: counts all of them for a customer with 5000 orders
SELECT c.*
FROM customers c
WHERE (SELECT count(*) FROM orders o
       WHERE o.customer_id = c.id AND o.status = 'PAID') > 0;

-- good: stops after finding the first one
SELECT c.*
FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o
              WHERE o.customer_id = c.id AND o.status = 'PAID');

Inside EXISTS, SELECT 1, SELECT * or SELECT id make no difference, since the columns aren't read at all.

PostgreSQL turns EXISTS into a semi-join, so customers aren't repeated in the result. If you write a plain JOIN, a customer with three paid orders shows up three times, and then you have to add DISTINCT.

The same mistake exists in Java: instead of repository.countByCustomerId(id) > 0, write existsByCustomerIdAndStatus(id, PAID) in Spring Data, which sends a query with LIMIT 1.