
Predict
The Island With No Deliveries
A plain JOIN keeps only rows that match on both sides.
A LEFT JOIN keeps every row from the left table. When there's
no match, the right table's columns are filled with NULL
(Python's None).
Gull hasn't had a single delivery. Watch what happens to it.
(executescript runs several statements separated by ;.)
import sqlite3
conn = sqlite3.connect(":memory:")
conn.executescript("""
CREATE TABLE islands (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE deliveries (id INTEGER PRIMARY KEY,
island_id INTEGER, crates INTEGER);
INSERT INTO islands VALUES (1, 'Amber'), (2, 'Fog'), (3, 'Gull');
INSERT INTO deliveries VALUES (1, 1, 5), (2, 1, 2), (3, 2, 4);
""")
rows = conn.execute("""
SELECT i.name, COUNT(d.id)
FROM islands AS i
LEFT JOIN deliveries AS d ON d.island_id = i.id
GROUP BY i.id
ORDER BY i.name
""").fetchall()
print(rows)