Become a data analyst in 90 days✦27 portfolio projects✦100+ interview Q&As✦1:1 mentor for a year✦See the 90-Day System →✦Become a data analyst in 90 days✦27 portfolio projects✦100+ interview Q&As✦1:1 mentor for a year✦See the 90-Day System →✦
New here? Want every day planned for you? See the 90-Day System →

Free PDF · SQL

3 customers. 4 rows back. Why?

The JOIN question that shows if you really get joins: INNER vs LEFT, the WHERE trap, and counting customers with zero orders.

DGSQLINNER vs LEFT JOIN3 checks@thedataguy16

3 customers. LEFT JOIN gave back 4 rows. Why?

Because Asha has 2 orders. One-to-many joins repeat the left row. That is not a bug, and the interviewer wants you to say it.

Inside: INNER vs LEFT, the WHERE filter that quietly turns your LEFT JOIN into an INNER JOIN, and how to count orders per customer with zero included.

Save this for your next SQL round.

customers LEFT JOIN orders

nameorder_idamount
Asha101500
Asha102300
Ravi103700
NehaNULLNULL

Asha has 2 orders, so she shows up twice. Neha has none, so LEFT JOIN keeps her with NULLs.

INNER vs LEFT

INNER JOINLEFT JOIN
KeepsMatches onlyEvery left row
No matchRow droppedNULLs on the right
NehaGoneKept
Rows here34

Row count grows when the key repeats on the right side. That is one-to-many, not a bug.

The trap: WHERE on the right table

looks_like_left.sql

-- Neha vanishes: acts like INNER
SELECT c.name, o.amount
FROM customers c
LEFT JOIN orders o
  ON o.cust_id = c.id
WHERE o.amount > 400;

Neha's amount is NULL. NULL > 400 is not true, so WHERE throws her out.

The fix: move it to ON

real_left_join.sql

SELECT c.name, o.amount
FROM customers c
LEFT JOIN orders o
  ON o.cust_id = c.id
 AND o.amount > 400;

Result: Asha 500, Ravi 700, Neha NULL. Every customer stays.

Orders per customer, zero included

orders_per_customer.sql

SELECT c.id, c.name,
  COUNT(o.order_id) AS orders
FROM customers c
LEFT JOIN orders o
  ON o.cust_id = c.id
GROUP BY c.id, c.name;

COUNT(*) gives Neha 1. COUNT(o.order_id) skips NULLs and gives 0.

Which JOIN when

You needWrite
Only customers who orderedINNER JOIN
All customers, orders or notLEFT JOIN
Customers who never orderedLEFT JOIN + WHERE o.order_id IS NULL
Rows went up after a joinCheck if the key repeats

Say this in the interview

Wrong

  • Filter the right table in WHERE
  • COUNT(*) after a LEFT JOIN
  • Expect row count to stay the same

Right

  • Put that filter in ON
  • COUNT a column from the right table
  • Check keys for one-to-many first
Try it Find customers who never ordered, on real tables. Open the SQL playground →

Free PDF

INNER vs LEFT JOIN: the JOIN sheet

Download the PDF

Opens in Google Drive. No sign-up.

Keep going

More free PDFs

90-Day System · become a data analyst→