runtime
19 / 88

lesson 19 Joins & sets · intermediate

Keep unmatched rows

Keep rows even when the other table has no match.

the idea

LEFT JOIN keeps every row from the left table. When no match exists, right-side columns are NULL. A right-table filter in WHERE may remove those unmatched rows.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

customers4 columns · 8 rows
idinteger · keynametextcitytextjoined_attext
1AliceChicago2024-01-10
2BenAustin2024-02-12
3CaraSeattle2024-03-05
4DevChicago2024-04-20
5ElenaNULL2024-05-01

showing 5 of 8 rows

orders6 columns · 12 rows
idinteger · keycustomer_idintegerproduct_idintegerquantityintegerstatustextordered_attext
101112paid2025-01-01
102231paid2025-01-02
103121paid2025-01-05
104352pending2025-01-08
105445paid2025-02-01

showing 5 of 12 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
SELECT c.name, COUNT(o.id) AS order_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name;

Watch for: Using INNER JOIN loses Hugo, who has no orders.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. Identify the preserved side. Every customer must stay, even Hugo without an order.

    step-1.sql
    SELECT *
    FROM customers;
  2. Inspect the joined rows. Customers repeat for each order. Hugo gets a NULL right-side id.

    step-2.sql
    SELECT c.id,c.name,o.id AS order_id
    FROM customers c
    LEFT JOIN orders o ON o.customer_id=c.id;
  3. Count matching right-side ids. COUNT(o.id) ignores the unmatched NULL and gives Hugo zero.

    step-3.sql
    SELECT c.name,COUNT(o.id) AS order_count
    FROM customers c
    LEFT JOIN orders o ON o.customer_id=c.id
    GROUP BY c.id,c.name;

challenge 1

Show every customer name and order_count, including customers with zero orders.

Return nameorder_countany row order

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.