Skip to content
Optimal Lab

Databases · interactive

Tables, keys and relations

Five orders from three customers. Store them in one sheet and Ada's email is copied three times. Split them into two tables linked by a key and every fact lives in one place. Try each statement and see what the database allows.

customers

id (PK)nameemail
1Adaada@new.io
2Bobo@mail.com
3Cycy@mail.com

orders

idcustomer_id (FK)total
101140.00
102215.50
103122.00
10439.99
105161.25

The same data in one flat sheet

ordernameemailtotal
101Adaada@mail.com40.00
102Bobo@mail.com15.50
103Adaada@mail.com22.00
104Cycy@mail.com9.99
105Adaada@mail.com61.25

The flat sheet repeats Ada's email on 3 rows. Miss one and the data disagrees with itself.

UPDATE 1. One cell changed, and every order of Ada's sees the new email through the key.

Run a statement

UPDATE customers SET email = 'ada@new.io' WHERE id = 1;
  1. 1

  2. 2

    Customer details live in customers. Orders keep only the customer's id, not a copy of their name and email.

    Copies of Ada's email: 3 in the flat sheet, 1 in customers.

  3. 3

  4. 4

  5. 5

In production

Tools and technologies

Primary and foreign keys work the same way in every relational database.

Not tied to one language — use these names when you search docs or design a system.