MintQueryStart free
← All guides

Why does my LEFT JOIN behave like an INNER JOIN?

Your LEFT JOIN behaves like an INNER JOIN because of a WHERE condition on the right-hand table. The LEFT JOIN keeps the unmatched rows and fills them with NULL, and then WHERE throws those rows away, because NULL never equals anything. Move the condition from WHERE into ON.

How it usually happens

The first version of the query works: every customer is there, with or without orders. Then the request changes a little. Only paid orders should count. You add one line at the bottom, WHERE o.status = 'paid', and half the customers are gone. The join still says LEFT.

The tables

customers
idname
1Ana
2Ben
3Chloe
4Dev
orders
order_idcustomer_idstatus
1011paid
1021refunded
1032refunded
1043paid

Ben's only order was refunded. Dev has no orders.

The query that loses customers

SELECT c.name, o.order_id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.status = 'paid'
ORDER BY c.name;
nameorder_id
Ana101
Chloe104

Ben and Dev should be in the list with no order next to them.

What the join returns before the WHERE

nameorder_idstatus
Ana101paid
Ana102refunded
Ben103refunded
Chloe104paid
DevNULLNULL

The LEFT JOIN did keep Dev. WHERE runs after the join and checks every row. Dev's status is NULL, and NULL = 'paid' is not true, so Dev goes. Ben's only row says refunded, so Ben goes too.

The fix

SELECT c.name, o.order_id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
                  AND o.status = 'paid'
ORDER BY c.name;
nameorder_id
Ana101
BenNULL
Chloe104
DevNULL

In ON, the condition decides which orders match. A customer with no matching order still stays, with NULL.

Rule to remember: after a LEFT JOIN, conditions on the right-hand table go in ON, and conditions on the left-hand table go in WHERE. The one exception is WHERE o.order_id IS NULL, which you write on purpose to find the rows with no match.

Try it yourself

Same trap, different tables. An office has four meeting rooms and a short list of bookings.

rooms
idname
1Birch
2Cedar
3Maple
4Oak
bookings
booking_idroom_idday
11Mon
21Tue
32Tue
43Mon

The query below is meant to list every room with its Monday booking, as room and booking_id, sorted by room. Rooms that are free on Monday should show NULL. Cedar and Oak are missing. Fix it.

Hint

The day condition is about bookings, the right-hand table. Where does it run now?

Show solution
SELECT r.name AS room, b.booking_id
FROM rooms r
LEFT JOIN bookings b ON b.room_id = r.id
                   AND b.day = 'Mon'
ORDER BY r.name;
roombooking_id
Birch1
CedarNULL
Maple4
OakNULL

MintQuery has 500+ exercises like this one, in lessons of a few minutes.

Start freeGet the app