Español Practice SQL

LEFT JOIN or INNER JOIN? A plain explanation with examples

The difference is one question: what should happen to rows that have no match?

INNER JOIN keeps only rows that match on both sides. LEFT JOIN keeps every row of the first table and fills the other side with NULL when there is no match.

Use INNER JOIN when

  • You only care about rows that have a match, such as invoices with their customer.
  • A missing match means bad data you want to leave out.

Use LEFT JOIN when

  • Every row of the first table must stay, such as every customer, even without invoices.
  • You want to find what is missing.
SELECT c.customer_name
FROM customers c
LEFT JOIN invoices i ON i.customer_id = c.customer_id
WHERE i.invoice_id IS NULL

The COUNT(*) trap

After a LEFT JOIN, a customer with no invoices still has one row, so COUNT(*) shows 1. Count a column from the second table instead, COUNT(i.invoice_id), and you get the honest 0.

Practice what you just read

Open the practice

Guides for this article

More articles