If you are learning SQL, one of the most common early bugs happens when you try to count related rows across two tables. Suppose you have a courses table and a lessons table, and you want a summary showing every course alongside how many lessons it currently has.
Many beginners write INNER JOIN with COUNT(*)—and accidentally hide every brand-new course that has 0 lessons. Here is how LEFT JOIN + COUNT(child.id) fixes both bugs cleanly.
1. Set Up a Reproducible Example
You can run this directly with Python's built-in sqlite3 module without installing any database server:
import sqlite3 db = sqlite3.connect(":memory:") db.executescript(""" CREATE TABLE courses (id INTEGER PRIMARY KEY, name TEXT); CREATE TABLE lessons (id INTEGER PRIMARY KEY, course_id INTEGER, title TEXT); INSERT INTO courses VALUES (1, 'Python'), (2, 'SQL'), (3, 'Rust'); INSERT INTO lessons VALUES (1, 1, 'Variables'), (2, 1, 'Loops'), (3, 2, 'SELECT'); """) Notice that Rust (id = 3) has zero lessons yet.
2. Two Traps Beginners Hit
Trap A: Using INNER JOIN
An INNER JOIN only keeps rows that match on both sides. Rust has no matching row in lessons, so Rust vanishes completely from your report.
Trap B: Switching to LEFT JOIN, but keeping COUNT(*)
If you switch to LEFT JOIN and keep COUNT(*), SQL returns 1 for Rust instead of 0! Why? Because LEFT JOIN still outputs one row for Rust with NULL in all lessons columns, and COUNT(*) counts rows—even when the joined columns are NULL.
3. The Clean Fix: LEFT JOIN + COUNT(l.id)
Instead of COUNT(*), count a non-null column from the right (child) table, such as l.id. In SQL, COUNT(column) ignores NULL values:
rows = db.execute(""" SELECT c.name, COUNT(l.id) AS lesson_count FROM courses c LEFT JOIN lessons l ON l.course_id = c.id GROUP BY c.id, c.name ORDER BY c.id """).fetchall() print(rows) # [('Python', 2), ('SQL', 1), ('Rust', 0)] Now:
-
Pythonshows2 -
SQLshows1 -
Ruststays in the report with0
4. Watch Out for WHERE vs ON
If you ever need to filter the child table (for example, counting only published = 1 lessons), put that filter inside the ON clause (AND l.published = 1), not in a WHERE clause. Putting WHERE l.published = 1 after a LEFT JOIN filters out all NULL unmatched rows and silently turns your LEFT JOIN back into an INNER JOIN.
If you are self-teaching SQL, Python, Web Dev, or Computer Science fundamentals and want structured, zero-paywall step-by-step guides, I've also been organizing free tutorials at HowCodex. What SQL concept tripped you up the most when starting out?