DataTalksWithSaud

Why your SQL LEFT JOIN drops rows

Learn where to put a filter when you need to keep customers who have no matching orders.

Suppose you want every customer and the number of completed orders for each, including a zero for customers with no completed orders. Start by deciding what one output row represents: one customer.

Put the order filter in the join condition

SELECT c.customer_id, COUNT(o.order_id) AS completed_orders
FROM customers AS c
LEFT JOIN orders AS o
    ON o.customer_id = c.customer_id
   AND o.status = 'completed'
GROUP BY c.customer_id;

The join retains customers even when it finds no completed order. For those customers the order columns are NULL, so COUNT(o.order_id) returns zero. Use a non-null order key for the count. COUNT(*) would count the retained customer row even when no order matched.

Test your assumptions with three customers

Try one customer with two completed orders, one with a pending order and one with no orders. You should see counts of 2, 0 and 0. Moving the status condition into WHERE drops the two zero rows because the unmatched order status is NULL.

Joins in the PostgreSQL documentation

Analytics preferences

You can allow Google Analytics to measure visits and resource clicks. Either choice lets you use the whole site.