BeginnerLesson 2 of 127 min read

Data Modelling: From a Messy Spreadsheet to Related Tables

Turn a flat volunteer spreadsheet into related tables with primary and foreign keys, see the update and delete anomalies that the flat sheet causes, and verify the relational design with queries checked against plain Python.

In this lesson you will

  • Identify entities and relations
  • Use keys and junction tables
  • Recognise anomalies in flat data
  • Check a model with queries

About 28 minutes

One sheet, three people editing

Tomás’s sheet has one row per signup: the volunteer’s name, phone, the shift date, the shift’s place and its capacity. It works until it does not. Ana changes her phone number, and Tomás updates three of her five rows. The Saturday shift moves to another hall and four of twelve rows keep the old place. The last volunteer for a shift is deleted, and the shift itself disappears from the sheet. These are anomalies of flat data: the same fact stored in many places drifts apart. The cure is data modelling: store each fact once, in a table of its own, and link the tables.

Start by listing the entities, the things you keep information about: volunteers, shifts, stock items. Each becomes a table, with one row per thing, and each row gets a primary key, a unique identifier. Relations between entities become links. A shift belongs to one place, a one-to-many relation, stored as a column in the shift row that holds the place’s key, called a foreign key. A volunteer can sign up for many shifts and a shift has many volunteers, a many-to-many relation, which needs a junction table with one row per signup holding both keys. No-code tools show these as “linked record” or “relation” fields, and under the hood they are keys. Good models make questions easy: “who is on Saturday?” is a join of the signups with the volunteers, filtered by the shift.

Relation Example How it is stored
One-to-many A place has many shifts Foreign key place_id in shifts
Many-to-many Volunteers and shifts Junction table signups(volunteer_id, shift_id)
One-to-one A volunteer and a private profile Same key, or one foreign key with unique
Lookup The shift’s place name in the signup view Join through the keys
import sqlite3, json
db = sqlite3.connect(":memory:"); db.execute("PRAGMA foreign_keys = ON")
db.executescript("""
CREATE TABLE places     (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE);
CREATE TABLE volunteers (id INTEGER PRIMARY KEY, name TEXT NOT NULL, phone TEXT);
CREATE TABLE shifts     (id INTEGER PRIMARY KEY, day TEXT NOT NULL, place_id INTEGER NOT NULL REFERENCES places(id), capacity INTEGER NOT NULL CHECK (capacity > 0));
CREATE TABLE signups    (volunteer_id INTEGER NOT NULL REFERENCES volunteers(id), shift_id INTEGER NOT NULL REFERENCES shifts(id), PRIMARY KEY (volunteer_id, shift_id));
""")
db.executemany("INSERT INTO places VALUES (?,?)", [(1, "Hall A"), (2, "Hall B")])
db.executemany("INSERT INTO volunteers VALUES (?,?,?)", [(1, "Ana", "555-0101"), (2, "Ben", "555-0102"), (3, "Chi", "555-0103"), (4, "Dee", "555-0104")])
db.executemany("INSERT INTO shifts VALUES (?,?,?,?)", [(1, "2024-03-09", 1, 3), (2, "2024-03-10", 2, 2), (3, "2024-03-16", 1, 2)])
db.executemany("INSERT INTO signups VALUES (?,?)", [(1, 1), (2, 1), (3, 1), (1, 2), (4, 2), (1, 3)])
q = lambda s, a=(): db.execute(s, a).fetchall()
on_sat = q("SELECT v.name FROM signups s JOIN volunteers v ON v.id = s.volunteer_id WHERE s.shift_id = 1 ORDER BY v.name")
fill = q("SELECT s.day, p.name, COUNT(g.volunteer_id), s.capacity FROM shifts s JOIN places p ON p.id = s.place_id LEFT JOIN signups g ON g.shift_id = s.id GROUP BY s.id ORDER BY s.day")
db.execute("UPDATE volunteers SET phone = '555-0199' WHERE name = 'Ana'")          # one fact, one place
ana = q("SELECT v.name, v.phone, COUNT(*) FROM volunteers v JOIN signups s ON s.volunteer_id = v.id WHERE v.name = 'Ana' GROUP BY v.id")
db.execute("UPDATE places SET name = 'Community Hall' WHERE id = 1")               # rename once, every shift follows
moved = q("SELECT s.day, p.name FROM shifts s JOIN places p ON p.id = s.place_id ORDER BY s.day")
try: db.execute("INSERT INTO signups VALUES (9, 1)")
except sqlite3.IntegrityError as e: fk = str(e)
try: db.execute("INSERT INTO signups VALUES (1, 1)")
except sqlite3.IntegrityError as e: dup = str(e)
free = q("SELECT s.day, s.capacity - COUNT(g.volunteer_id) FROM shifts s LEFT JOIN signups g ON g.shift_id = s.id GROUP BY s.id ORDER BY s.day")
print("on shift 1:", [r[0] for r in on_sat]); print("fill:", fill); print("Ana after the phone change:", ana); print("shifts after renaming Hall A:", moved)
print("unknown volunteer refused:", fk, "| duplicate signup refused:", dup); print("free places:", free)
print("DATA " + json.dumps({"on": [r[0] for r in on_sat], "fill": fill, "ana": ana, "moved": moved, "fk": fk, "dup": dup, "free": free}))
on shift 1: ['Ana', 'Ben', 'Chi']
fill: [('2024-03-09', 'Hall A', 3, 3), ('2024-03-10', 'Hall B', 2, 2), ('2024-03-16', 'Hall A', 1, 2)]
Ana after the phone change: [('Ana', '555-0199', 3)]
shifts after renaming Hall A: [('2024-03-09', 'Community Hall'), ('2024-03-10', 'Hall B'), ('2024-03-16', 'Community Hall')]
unknown volunteer refused: FOREIGN KEY constraint failed | duplicate signup refused: UNIQUE constraint failed: signups.volunteer_id, signups.shift_id
free places: [('2024-03-09', 0), ('2024-03-10', 0), ('2024-03-16', 1)]

The model has four tables: places, volunteers, shifts and signups, the junction table for the many-to-many relation. The query for the first shift joins the signups to the volunteers and returns Ana, Ben, Chi. The fill report counts the signups of every shift against its capacity: 2024-03-09 at Hall A: 3 of 3; 2024-03-10 at Hall B: 2 of 2; 2024-03-16 at Hall A: 1 of 2. The two experiments below that show the point of the design. Ana’s phone number was changed in one row, and all her 3 signups now show the new number, 555-0199, because the number is stored once. Hall A was renamed to Community Hall in one row, and both of its shifts follow it, where the flat sheet would have needed many edits and would have left some behind.

The model also protects the data. A signup for a volunteer who does not exist was refused with “FOREIGN KEY constraint failed”: the foreign key insists that every signup points at a real volunteer and a real shift. A second signup of Ana on the same shift was refused with “UNIQUE constraint failed: signups.volunteer_id, signups.shift_id”, since the pair of keys is the primary key of the junction table, so a person cannot take two places on one shift. The capacity column has a rule that it must be above zero. In a no-code tool the same protection appears as required fields, unique fields and linked record fields that only accept existing records, and it is worth switching them on, since a rule stated once is enforced everywhere.

Independent check: the same questions were answered in plain Python from dictionaries and lists that hold the same data, without SQL: who is on the first shift, how many are signed up for each shift against its capacity, the free places, and the effect of changing a phone number and a place name. All results agree with the database’s. Note that the free places reported by the database, 0 for Saturday the 9th, 0 for the 10th and 1 for the 16th, come out of one subtraction from the capacity, so the sign-up form can refuse a signup for a full shift.

Check by hand: Saturday the 9th has three signups, Ana, Ben and Chi, against a capacity of 3, so it is full. The 10th has Ana and Dee against 2, also full, and the 16th has only Ana against 2, so one place is free. Ana has three signups in all.

Do not copy data into several places

If a fact appears in two tables, it will eventually disagree with itself. Store it once and link to it. Copies for reports can be calculated, and not typed.

Give every table a real key and use linked fields

Names change and are not unique. Let the platform keep an internal id, and show the name through a lookup. Use linked record fields, not text, to connect tables.

About this course

No-code platforms, plans and limits change often, so the lessons describe categories of tools with generic names and you must check each vendor’s current website. The ideas of this course, data tables, forms, views, automations and permissions, are what the tools implement, so the lesson reproduces them in small programs, run in Python 3.13 or Node.js 22 on sample data, with a second independent calculation. Different platforms use different words: base, table, sheet, collection, linked record, relation, reference. The ideas are the same.

Practice

Model a library of tools to lend, with tools, members and loans, on paper, listing the keys. Find the junction table in your own example. Add a place for stock items to be stored and decide which relation that is.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What is a foreign key?

  1. A secret password
  2. A column that is sorted
  3. A column that holds the key of a row in another table
  4. A copy of a table

It links tables.

What does a junction table store?

  1. The biggest table
  2. One row per link in a many-to-many relation
  3. A backup
  4. Only names

signups(volunteer_id, shift_id).

Why is a flat spreadsheet risky for related data?

  1. It is too small
  2. The same fact is stored in many places and drifts apart
  3. It is not free
  4. It cannot sort

Update and delete anomalies.

What did the primary key on (volunteer_id, shift_id) prevent?

  1. The same person taking two places on one shift
  2. Deleting a volunteer
  3. Sorting
  4. Printing

A unique pair.

Why answer the questions in plain Python too?

  1. An independent check of the model and the queries
  2. To avoid SQL
  3. It is faster
  4. It is required

Same data, different method.

Summary

  • Store each fact once, and link tables with keys.
  • One-to-many uses a foreign key; many-to-many uses a junction table.
  • Constraints protect the data: required, unique, linked.
  • Check the model with queries and an independent calculation.

Next lesson

Lesson 3 covers formulas, and how they map to queries.

Questions

How many tables does an app need?

As many as it has kinds of things. Small apps often have three to eight. More tables are fine if each holds one kind of thing.

What is a lookup or rollup field?

A field that shows a value from a linked record, or a summary of linked records, such as the number of signups of a shift. The platform calculates it from the keys.

Can I change the model later?

Yes, but with more work as data grows, so spend an hour on a paper model first.

Progress is saved in this browser.