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

Help the database find the door.

Create an index aligned with a query and inspect its presence and plan.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

An index is an additional data structure that can reduce the work of finding qualifying rows. It costs storage and makes writes more expensive to maintain. A composite index has an order: which leading columns a query constrains affects its usefulness. Explain plans show how the optimizer intends to access data, but a tiny teaching dataset is not meaningful performance evidence.

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

with mysql_lab() as (connection, cursor):
    cursor.execute("CREATE INDEX idx_task_state_minutes ON lab_tasks (done, minutes)")
    cursor.execute("SHOW INDEX FROM lab_tasks WHERE Key_name = %s", ("idx_task_state_minutes",))
    print([row["Column_name"] for row in cursor.fetchall()])
    cursor.execute("EXPLAIN SELECT id, name FROM lab_tasks WHERE done = %s AND minutes >= %s", (False, 20))
    plan = cursor.fetchall()
    print("plan available:", bool(plan))
↳ EXPECTED OUTPUT
['done', 'minutes']
plan available: True

03 Under the hood

  1. 1

    The index begins with done, followed by minutes. It can support a state equality plus a duration range, but the optimizer may prefer a scan for four rows.

  2. 2

    SHOW INDEX reports index metadata, including one entry per indexed column. A plan being available does not imply the index was selected.

  3. 3

    Evaluate representative data, query frequency, selectivity, write cost, and real plans before adding indexes. Avoid creating an index for every column without an observed access pattern.

04 Your turn, builder

A SMALL MISSION

Create an index on project_id and verify that its metadata exists.

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

with mysql_lab() as (connection, cursor):
    cursor.execute("CREATE INDEX idx_task_project ON lab_tasks (project_id)")
    cursor.execute("SHOW INDEX FROM lab_tasks WHERE Key_name = %s", ("idx_task_project",))
    print(bool(cursor.fetchall()))

05 Check your signal

QUICK SIGNAL CHECK

What is a trade-off of adding an index?

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.