basics05Chapter 5 of 6

Joins

A join puts rows of two tables side by side wherever the ON condition matches. The join type decides what happens to the rows that find no partner.

The data

A small slice of the Byte Shop: four customers and five orders. Anna has two orders. Deniz has none. Order 6 belongs to customer 9, who is not in the slice.

The join lab

Switch the join type. Lines show the pairs that match, and the result below is what SQLite returns for the query.

join-labSQLite
Join type

LEFT JOINEvery row of the left table, customers, with its partner if there is one, otherwise with NULL.

customers AS c

orders AS o

matches1Anna Becker
matches2Ben Okafor
matches3Chiara Rossi
stays, with NULL4Deniz Kaya
matches11
matches23
matches32
left out69
matches71
  • matches
  • stays, with NULL
  • left out
query.sql
SELECT c.id, c.name, o.id, o.customer_id
FROM customers AS c
LEFT JOIN orders AS o
    ON o.customer_id = c.id;
result

Starting SQLite …

Step through the result to see where each row comes from.

5 rows. All four customers stay. Deniz has no order, so his order columns are NULL. Order 6 is left out.

RIGHT JOIN and FULL OUTER JOIN came to SQLite in version 3.39 (2022). This page runs a newer one, so all five work. Older SQLite only knows INNER, LEFT and CROSS: there you swap the two tables and write LEFT JOIN instead of RIGHT JOIN.

Why the circles are only a sketch

Join types are often drawn as two overlapping circles, like the small icons above. They help to remember which side stays. But they are not quite right:

  • A circle is a set of things. A join result is a list of pairs of rows.
  • In a set, Anna would sit in the overlap once. In the result she is there twice, once per order: with 1:n, rows repeat.
  • CROSS JOIN cannot be drawn with circles at all.

So: the circles to remember which side stays, the tables to see what really comes out.

A table joined with itself

A self join uses the same table twice, under two names. Here: which customers live in the same city? a.id < b.id keeps each pair once and stops Anna from pairing with herself.

self-join.sqlbyte-shop.db
SELECT a.name, b.name, a.city
FROM customers AS a
JOIN customers AS b
    ON a.city = b.city AND a.id < b.id;