Database Design Project · Lesson 110 of 112

Database Project Tables, Keys and Relationships

What you will learn

  • How to turn entities into CREATE TABLE statements
  • Where primary keys, foreign keys and rules go
  • How to load sample data
  • How to test that the rules really refuse bad data

1. The design

From lesson 15.1:

customers (1) ----< orders (1) ----< order_items >---- (1) garments

One customer has many orders; one order has many items; one garment appears in many items. The pairs (order, garment) identify an item.

2. The tables

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("PRAGMA foreign_keys = ON")
con.executescript("""
CREATE TABLE customers (
    id    INTEGER PRIMARY KEY,
    name  TEXT NOT NULL,
    phone TEXT NOT NULL UNIQUE
);
CREATE TABLE garments (
    id    INTEGER PRIMARY KEY,
    name  TEXT NOT NULL UNIQUE,
    price INTEGER NOT NULL CHECK (price > 0)
);
CREATE TABLE orders (
    id          INTEGER PRIMARY KEY,
    customer_id INTEGER NOT NULL REFERENCES customers(id),
    ordered_on  TEXT NOT NULL,
    due_on      TEXT NOT NULL,
    status      TEXT NOT NULL DEFAULT 'new' CHECK (status IN ('new', 'sewing', 'ready', 'collected')),
    CHECK (due_on >= ordered_on)
);
CREATE TABLE order_items (
    order_id   INTEGER NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
    garment_id INTEGER NOT NULL REFERENCES garments(id),
    quantity   INTEGER NOT NULL CHECK (quantity > 0),
    unit_price INTEGER NOT NULL CHECK (unit_price > 0),
    PRIMARY KEY (order_id, garment_id)
);
""")
print([r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")])
['customers', 'garments', 'order_items', 'orders']

How each requirement is met:

Requirement In the tables
R1 phone unique phone TEXT NOT NULL UNIQUE
R2 garments with price garments.price, must be above 0
R3 order fields and status orders, with CHECK (status IN (...)) and a default of 'new'
R4 many garments per order the order_items junction table, keyed by (order_id, garment_id)
R5 price at the time order_items.unit_price, a copy made when the item is added
R6 due not before ordered CHECK (due_on >= ordered_on)

Details to notice:

  • Dates are stored as text in the form 2026-03-01 (year-month-day), which sorts correctly as text. SQLite has no separate date type.
  • Prices are whole taka in INTEGER, which avoids the rounding problems of decimals (lesson 2.2).
  • ON DELETE CASCADE on the items means deleting an order deletes its items. The other links have no cascade, so you cannot delete a customer who has orders.
  • PRAGMA foreign_keys = ON is needed in SQLite every time you connect, otherwise foreign keys are not checked.

3. Sample data

con.executescript("""
INSERT INTO customers VALUES (1,'Rina Akter','01711000001'),(2,'Sam Roy','01711000002'),(3,'Lee Khan','01711000003');
INSERT INTO garments VALUES (1,'Shirt',800),(2,'Trousers',1000),(3,'Panjabi',1500);
INSERT INTO orders VALUES (1,1,'2026-03-01','2026-03-10','sewing'),(2,1,'2026-03-05','2026-03-15','new'),(3,2,'2026-03-02','2026-03-09','ready');
INSERT INTO order_items VALUES (1,1,2,800),(1,2,1,1000),(2,3,1,1500),(3,1,1,750);
""")

All names, phone numbers and prices are made up. Order 3 contains a shirt at 750, while the garment list now says 800: that is R5 at work, an old price kept on an old order.

In a real program you would not type unit_price by hand. The program copies the garment's current price into the item at the moment the item is added, for example with INSERT ... SELECT:

INSERT INTO order_items (order_id, garment_id, quantity, unit_price)
SELECT 1, id, 2, price FROM garments WHERE name = 'Shirt'

Run on a fresh copy of the tables with a shirt priced 800, then followed by UPDATE garments SET price = 900 WHERE name = 'Shirt', a join of the item with its garment shows [(800, 900)]: the item kept 800 while the garment now costs 900.

4. Try to break it

for sql in [
    "INSERT INTO customers VALUES (4,'Amy','01711000001')",
    "INSERT INTO orders (customer_id, ordered_on, due_on) VALUES (9,'2026-03-01','2026-03-05')",
    "INSERT INTO orders (customer_id, ordered_on, due_on) VALUES (1,'2026-03-10','2026-03-05')",
    "INSERT INTO orders (customer_id, ordered_on, due_on, status) VALUES (1,'2026-03-01','2026-03-05','lost')",
    "INSERT INTO order_items VALUES (1,1,0,800)",
]:
    try:
        con.execute(sql)
        print("accepted")
    except sqlite3.IntegrityError as e:
        print("refused:", e)
refused: UNIQUE constraint failed: customers.phone
refused: FOREIGN KEY constraint failed
refused: CHECK constraint failed: due_on >= ordered_on
refused: CHECK constraint failed: status IN ('new', 'sewing', 'ready', 'collected')
refused: CHECK constraint failed: quantity > 0

Five bad rows, five refusals: a repeated phone, a customer who does not exist, a due date before the order date, a made-up status, and a quantity of zero. These are the rules of lessons 2.7 and 3.5 doing their job. Always test your rules like this; a rule that was never tried is only a hope.

Worked example: add a requirement

The owner now wants to record a delivery note on each order. This is one nullable column. In a new session you would write:

ALTER TABLE orders ADD COLUMN note TEXT

Run on a copy of the tables, PRAGMA table_info(orders) then lists the column names ['id', 'customer_id', 'ordered_on', 'due_on', 'status', 'note'], and an old order reads back as (1, None). None is NULL, which means "no note", and nothing else changes. Adding a column is easy; changing the meaning of existing data is the risky kind of change (lesson 8.7).

Common mistakes

  • Forgetting PRAGMA foreign_keys = ON in SQLite, so foreign keys silently do nothing.
  • Storing only the garment's current price and letting old orders change when prices change.
  • Putting the rules only in the program. Put them in the tables too.
  • Never testing the rules.

Key takeaways

  • Each entity becomes a table with a primary key; each link becomes a foreign key; a many-to-many link becomes a junction table.
  • Put the rules in the table definitions: UNIQUE, NOT NULL, CHECK, DEFAULT, REFERENCES.
  • Keep copies of values that must not change later, such as the price at ordering.
  • Test the rules by trying to break them.

Practice

1. What is the primary key of order_items, and why?

Show answer

(order_id, garment_id): one row per garment in an order.

2. Which rule refused the second bad row, and what was wrong with it?

Show answer

The foreign key; customer 9 does not exist.

3. Why does order_items have its own unit_price?

Show answer

To keep the price at the time of ordering (R5), unaffected by later changes to garments.price.

4. What does ON DELETE CASCADE do on order_items.order_id?

Show answer

Deleting an order also deletes its items.

5. The owner says phone numbers are not always unique because a family shares one phone. Which rule must change, what else in the design is affected, and what would you check with the owner first?

Show answer

The UNIQUE on customers.phone (R1) must go or change, for example to unique on (name, phone). Anything that relied on a phone identifying one customer, such as looking a customer up by phone, is affected. Ask the owner what should identify a customer; a rule changes the business, so confirm it before editing the tables.

6. Why must you run PRAGMA foreign_keys = ON in SQLite?

Show answer

SQLite does not check foreign keys unless it is switched on for each connection.