Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Python meets MySQL
EXPERIMENT 84 / 101

Bring the records together.

Combine related tables and calculate one useful result per group.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

A join combines rows according to a relationship. An inner join retains matches; a left join retains every row on the left, adding NULL values when no right-side match exists. GROUP BY gathers rows for aggregate calculations. Join cardinality matters: an accidental many-to-many multiplication can inflate totals even when the SQL is syntactically valid.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

mysql_joins.py
from lab_support import mysql_lab

with mysql_lab() as (connection, cursor):
    cursor.execute("""SELECT p.name, SUM(t.minutes) AS minutes
    FROM lab_projects AS p
    JOIN lab_tasks AS t ON t.project_id = p.id
    WHERE t.done = %s
    GROUP BY p.id, p.name
    ORDER BY p.id""", (False,))
    for row in cursor.fetchall():
        print(row["name"], int(row["minutes"]))
↳ EXPECTED OUTPUT
Orbit 60
Atlas 30

03 Under the hood

  1. 1

    The ON condition expresses the project relationship. A missing join predicate would create combinations rather than related records.

  2. 2

    The WHERE filter removes completed tasks before aggregation, then SUM calculates the remaining effort per project.

  3. 3

    To retain projects with no unfinished tasks, use a LEFT JOIN and put the unfinished-task condition in the ON clause, with COALESCE around the aggregate. Putting that right-table filter in WHERE can eliminate the unmatched rows.

04 Your turn, builder

A SMALL MISSION

Count all tasks per project, retaining projects that might have no tasks.

Reveal one possible solution +
one_possible_solution.py
from lab_support import mysql_lab

with mysql_lab() as (connection, cursor):
    cursor.execute("SELECT p.name, COUNT(t.id) AS total FROM lab_projects p LEFT JOIN lab_tasks t ON t.project_id = p.id GROUP BY p.id, p.name ORDER BY p.id")
    for row in cursor.fetchall():
        print(row["name"], row["total"])

05 Check your signal

QUICK SIGNAL CHECK

What does a LEFT JOIN preserve?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.