Storing Data with SQL: Tables, Joins and Indexes
Store the tool library in a real SQL database, join tables, summarise with GROUP BY, see how an index changes the query plan, and verify every query result against a plain Python calculation.
In this lesson you will
- Design tables with keys
- Query with SELECT, JOIN and GROUP BY
- Use an index and read the query plan
- Check query results independently
About 28 minutes
A notebook that can answer questions
A dictionary in memory vanishes when the server restarts, so a real back end keeps its data in a database. A relational database stores data in tables, like spreadsheets with strict columns: each row is one record, each column has a type, and one column, the primary key, identifies the row. Tables are linked by foreign keys: a loan row stores the id of the tool and the id of the member, not their names, so a name is stored once and can be changed in one place. SQL, the language of relational databases, asks questions of the tables. SQLite, which comes with Python, is a complete database in a single file or in memory, and is a good place to learn.
Four kinds of query cover most of the work. SELECT with WHERE filters rows. JOIN combines rows of several tables by matching keys. GROUP BY with COUNT, SUM or AVG summarises groups. And ORDER BY with LIMIT sorts and takes the first rows. As a table grows, finding a row by scanning every row becomes slow, so you create an index on the columns you search by, a sorted structure that lets the database jump to the rows. EXPLAIN QUERY PLAN shows whether a query uses an index or scans the whole table.
| Concept | Example |
|---|---|
| Table | tools, members, loans |
| Primary key | tools.id |
| Foreign key | loans.tool_id refers to tools.id |
| Join | FROM loans JOIN tools ON loans.tool_id = tools.id |
| Index | CREATE INDEX idx_loans_member ON loans(member_id) |
import sqlite3, json
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE tools (id INTEGER PRIMARY KEY, name TEXT NOT NULL, kind TEXT NOT NULL);
CREATE TABLE members (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE loans (id INTEGER PRIMARY KEY, tool_id INTEGER NOT NULL REFERENCES tools(id), member_id INTEGER NOT NULL REFERENCES members(id), out_day INTEGER NOT NULL, back_day INTEGER);
""")
db.executemany("INSERT INTO tools VALUES (?,?,?)", [(1, "Drill", "power"), (2, "Ladder", "hand"), (3, "Sander", "power"), (4, "Saw", "hand")])
db.executemany("INSERT INTO members VALUES (?,?)", [(1, "Ama"), (2, "Ben"), (3, "Chi")])
db.executemany("INSERT INTO loans VALUES (?,?,?,?,?)", [(1, 1, 1, 1, 4), (2, 2, 2, 2, 9), (3, 1, 2, 5, 8), (4, 3, 1, 6, None), (5, 4, 3, 7, 10), (6, 1, 1, 9, None), (7, 2, 1, 10, None)])
q1 = db.execute("SELECT m.name, COUNT(*) FROM loans l JOIN members m ON m.id = l.member_id GROUP BY m.id ORDER BY COUNT(*) DESC, m.name").fetchall()
q2 = db.execute("SELECT t.name, m.name, l.out_day FROM loans l JOIN tools t ON t.id = l.tool_id JOIN members m ON m.id = l.member_id WHERE l.back_day IS NULL ORDER BY l.out_day").fetchall()
q3 = db.execute("SELECT t.kind, ROUND(AVG(l.back_day - l.out_day), 2) FROM loans l JOIN tools t ON t.id = l.tool_id WHERE l.back_day IS NOT NULL GROUP BY t.kind ORDER BY t.kind").fetchall()
q4 = db.execute("SELECT name FROM tools WHERE id NOT IN (SELECT tool_id FROM loans WHERE back_day IS NULL) ORDER BY name").fetchall()
print("loans per member :", q1)
print("still out :", q2)
print("avg days by kind :", q3)
print("on the shelf :", [r[0] for r in q4])
plan_before = [r[3] for r in db.execute("EXPLAIN QUERY PLAN SELECT * FROM loans WHERE member_id = 1")]
db.execute("CREATE INDEX idx_loans_member ON loans(member_id)")
plan_after = [r[3] for r in db.execute("EXPLAIN QUERY PLAN SELECT * FROM loans WHERE member_id = 1")]
print("plan without index:", plan_before)
print("plan with index :", plan_after)
print("DATA " + json.dumps({"q1": q1, "q2": q2, "q3": q3, "q4": [r[0] for r in q4], "before": plan_before, "after": plan_after}))
loans per member : [('Ama', 4), ('Ben', 2), ('Chi', 1)]
still out : [('Sander', 'Ama', 6), ('Drill', 'Ama', 9), ('Ladder', 'Ama', 10)]
avg days by kind : [('hand', 5.0), ('power', 3.0)]
on the shelf : ['Saw']
plan without index: ['SCAN loans']
plan with index : ['SEARCH loans USING INDEX idx_loans_member (member_id=?)']
The first query joined loans to members and counted per member: Ama has 4 loans, Ben has 2 loans, Chi has 1 loans. The second lists the loans that are still out, those with no return day: Sander with Ama since day 6; Drill with Ama since day 9; Ladder with Ama since day 10. The third averages the loan length by kind of tool, over returned loans only: hand 5 days, power 3 days. The fourth finds the tools on the shelf, those not in any open loan: Saw. Notice that NULL, the empty back_day, needed IS NULL, not = NULL, because a comparison with an unknown value is itself unknown.
The query plan shows what an index does. Before the index, SQLite reported “SCAN loans”, meaning that it read every row of the loans table to find the member. After CREATE INDEX, the plan became “SEARCH loans USING INDEX idx_loans_member (member_id=?)”, a direct lookup. With seven rows the difference is invisible, and with seven million it is the difference between milliseconds and many seconds. An index is not free: it takes space and slows down inserts a little, so add indexes for the columns that your queries actually filter and join on.
Independent check: the same four questions were answered in plain Python, with dictionaries and loops over the same seven loans, with no SQL at all, and each answer is identical to the database’s: the same counts per member, the same open loans in the same order, the same average days by kind, and the same shelf. If the SQL and the Python disagreed, one of them would contain a bug, so a second implementation is a good way to test a query.
Check by hand: Ama borrowed tools in loans 1, 4 and 6, and Ben in loans 2 and 3, Chi in loan 5 and Ama also in loan 7, which makes four loans for Ama, two for Ben and one for Chi. The open loans are 4, 6 and 7. Power tools, the drill and the sander, were returned after 3 and 3 days, so their average is 3.0, and the hand tools after 7 and 3 days, which averages 5.0.
Variables in your server disappear on a restart or a crash. Anything that must survive, such as loans, belongs in a database, and the database must be backed up.
NOT NULL, PRIMARY KEY, UNIQUE and FOREIGN KEY constraints reject bad data at the source, even when a bug or another program tries to write it.
Every program in this lesson was run while the course was written, with Python 3.13 and only its standard library (http.server, sqlite3, hashlib, hmac), with a real server on a free local port, and cross-checked with curl, openssl or a second implementation. Tools and versions change, so check the official documentation for current behaviour. SQLite is used for teaching and for small applications. Larger systems use servers such as PostgreSQL or MySQL, whose SQL is very similar but not identical, so check their documentation.
Practice
Write a query for the members who have never returned a tool late, if late means more than 5 days. Add a UNIQUE constraint on member names and watch an insert fail. Create an index on loans(tool_id) and read the plan of a query that filters by tool.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does a foreign key do?
- Encrypts data
- Sorts rows
- Deletes rows
- Links a row to a row of another table
loans.tool_id refers to tools.id.
How do you test for an empty (NULL) value?
- = NULL
- == NULL
- IS NULL
- EMPTY
Comparisons with NULL are unknown.
What does an index speed up?
- Inserts
- Backups
- Searches on the indexed column
- Table creation
At a small cost in space and insert time.
What does EXPLAIN QUERY PLAN show?
- The data
- How the database will run the query
- The table size
- The user
SCAN versus SEARCH using an index.
Why check query results in plain Python?
- SQL is wrong
- A second implementation finds bugs
- It is faster
- It is required
Independent verification.
Summary
- Tables hold rows; primary and foreign keys link them.
- SELECT, JOIN, GROUP BY and ORDER BY answer most questions.
- Indexes speed up searches; EXPLAIN QUERY PLAN shows their use.
- Verify queries with an independent calculation.
Questions
Do I need to learn SQL if I use an ORM?
Yes. An ORM builds SQL for you, and when queries are slow or wrong you need to read the SQL it produced.
SQLite or PostgreSQL?
SQLite for learning, tests and small single-server apps. PostgreSQL for larger systems with many users writing at once. Check each one's documentation for current features.
What is normalisation?
Splitting data into tables so that each fact is stored once, for example the member's name in the members table only.
