A Picture-by-Picture Guide to Keys Linking Two Tables

Primary keys and foreign keys are easier to see than to read about. Follow these described pictures with a pencil. By the end you will have drawn the pattern behind almost every database.

Picture 1: one table with a key

Draw a table called customers with three columns: id, name, city. Fill in three rows with ids 1, 2 and 3. Colour the id column yellow.

Caption: the yellow column is the primary key. Each value appears once and is never empty, so "customer 2" always means exactly one person.

Picture 2: a second table

Next to it, draw orders with columns id, customer_id, item. Fill in four rows:

idcustomer_iditem
1001Lamp
1011Rug
1023Chair
1032Desk

Colour the orders id yellow too, and the customer_id column green.

Caption: orders has its own primary key. The green column holds values copied from the customers' yellow column.

Picture 3: draw the arrows

From each green value, draw an arrow to the customer row with that id. Customer 1 gets two arrows.

Caption: the green column is a foreign key. It points from an order to the customer who placed it. One customer can have many orders; each order has one customer. This is called a one-to-many relationship.

Picture 4: the broken arrow

Add a fifth order with customer_id 9. Try to draw its arrow. There is no customer 9.

Caption: this is the mistake a foreign key constraint prevents. If you declare the rule, the database refuses the bad row:

CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL REFERENCES customers(id),
  item        TEXT NOT NULL
);

(In SQLite, foreign key checks only run after PRAGMA foreign_keys = ON;.)

Picture 5: deleting a customer

Cross out customer 1. Two arrows now point at nothing.

Caption: the database must decide what to do. By default it refuses the delete while orders still point there. You can instead ask it to delete the orders too (ON DELETE CASCADE) or to empty the pointer (ON DELETE SET NULL). For beginners, the default refusal is the safest.

Picture 6: following the arrows in SQL

Write this under your drawing:

SELECT customers.name, orders.item
FROM orders
JOIN customers ON customers.id = orders.customer_id;

Caption: a JOIN follows the arrows you drew, pairing each order with its customer.

Summary

ColourNameJob
YellowPrimary keyIdentifies one row in its own table
GreenForeign keyPoints to a row in another table
ArrowRelationshipHow the rows belong together

Next steps

Practise writing the JOIN in INNER JOIN and LEFT JOIN, one small step at a time, or add a key to your own tables with how to add a foreign key.

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.