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

Design the shape before the rows.

Create a table with explicit keys and reject values that violate its contract.

ADVANCED LAB
BY NAVAN SAMI◷ 11 MIN READPYTHON 3

01 The idea

A relational schema defines tables, columns, types, keys, and constraints. A primary key identifies a row; NOT NULL prevents absence in a column; CHECK can enforce a value rule on supported MySQL versions. Foreign keys represent referential integrity for suitable persistent tables. The workbench uses MySQL 8.4 and disposable temporary tables so you can explore DDL without replacing a real application table.

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_schema.py
from lab_support import mysql_lab

with mysql_lab() as (connection, cursor):
    cursor.execute("""CREATE TEMPORARY TABLE lab_notes (
        id INT PRIMARY KEY,
        title VARCHAR(80) NOT NULL,
        minutes INT NOT NULL CHECK (minutes >= 0)
    ) ENGINE=InnoDB""")
    cursor.execute("INSERT INTO lab_notes (id, title, minutes) VALUES (%s, %s, %s)", (1, "Plan", 15))
    cursor.execute("SELECT title, minutes FROM lab_notes WHERE id = %s", (1,))
    row = cursor.fetchone()
    print(row["title"], row["minutes"])
↳ EXPECTED OUTPUT
Plan 15

03 Under the hood

  1. 1

    DDL defines the structure. TEMPORARY limits this example’s table to the current connection; a normal application migration would create a persistent table without that keyword.

  2. 2

    The key prevents duplicate identifiers, and the nonnegative check constrains duration. Input validation is still useful for user-friendly errors, but database constraints protect every writer.

  3. 3

    Plan migrations explicitly. Many MySQL DDL statements cause implicit commits, and temporary-table operations have their own exceptions; do not assume schema changes roll back like ordinary row changes.

04 Your turn, builder

A SMALL MISSION

Create a temporary labels table with a unique name and insert one label.

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

with mysql_lab() as (connection, cursor):
    cursor.execute("CREATE TEMPORARY TABLE lab_labels (id INT PRIMARY KEY, name VARCHAR(50) NOT NULL UNIQUE)")
    cursor.execute("INSERT INTO lab_labels (id, name) VALUES (%s, %s)", (1, "urgent"))
    cursor.execute("SELECT name FROM lab_labels ORDER BY id")
    print(cursor.fetchone()["name"])

05 Check your signal

QUICK SIGNAL CHECK

What identifies a row through an enforced uniqueness rule?

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.