Primary Key & Foreign Key — Database

Primary key = a unique column that can't be NULL (empty), so one row can be pointed at for certain. Its kinds: auto-increment (a number the database fills…

Siti wants to close her Sunset Coffee account, and she has 2 orders. When her row is deleted from customers, what should happen to those orders: thrown away too, marked as "guest", or is the delete refused? The database can carry out that choice by itself, as long as you write the rule into the foreign key.

Two terms first, through Sunset Coffee's membership card. The card number is unique and never changes, even when the owner changes their name. The card number is the primary key of the customers table: a column (or a combination of columns) whose value is unique in every row, so one row can be pointed at for certain. Every receipt records only the member number from that card, not the customer's full details. A receipt is a row in orders, and the member number on it is a foreign key: a column holding another table's primary key. A foreign key is a pointer from a child row (here, an order) to its parent row (the customer who owns the order).

Primary key: every row's ID card

A primary key has two properties: it is unique and it can't be empty (NULL). SQLite has an exception: a primary key that isn't an INTEGER PRIMARY KEY can accept NULL unless you write NOT NULL. A table has only one primary key. Try adding a customer with the id Siti already uses (id 2). The -- line below it is the error SQLite replies with:

INSERT INTO customers (id, name) VALUES (2, 'Rina');
-- UNIQUE constraint failed: customers.id

There are four ways to choose a primary key:

Kind Example When to use it
Auto-increment id INTEGER PRIMARY KEY (SQLite), AUTO_INCREMENT (MySQL), GENERATED ALWAYS AS IDENTITY (PostgreSQL) the most common choice, the database fills in 1, 2, 3
UUID '3f2b9c1e-...', made by the app or by gen_random_uuid() in PostgreSQL ids created on many servers, or ids that mustn't be guessable from a URL
Natural key country code 'GB', 'JP' a real-world value guaranteed to be unique and never to change
Composite key PRIMARY KEY (order_id, product_id) in order_items linking tables, as in the Second Normal Form (2NF) lesson

A UUID is a long code (36 characters) that is practically never the same twice, even when it is made on many servers. Composite key is another name for a combined primary key.

Pick a value that never changes. Email and phone number look unique, but their owners can change them. When that happens, every foreign key pointing at them would have to change too. That's why most tables use an auto-increment id.

Foreign key: a pointer to another primary key

You already wrote foreign keys in the SQL lesson on table relationships. Here is Sunset Coffee's orders table, now with a rule for when its customer is deleted:

PRAGMA foreign_keys = ON;

CREATE TABLE customers (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);

CREATE TABLE orders (
  id INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id) ON DELETE SET NULL,
  total INTEGER NOT NULL
);

INSERT INTO customers VALUES (1, 'Budi'), (2, 'Siti'), (3, 'Andi');
INSERT INTO orders VALUES (1, 1, 1400), (2, 1, 550), (3, 2, 825), (4, 2, 450), (5, 3, 375);

INSERT INTO orders (customer_id, total) VALUES (9, 500);
-- FOREIGN KEY constraint failed

ON DELETE: what happens to the child rows

customers is the parent table. orders is the child table, because each of its rows points at one parent row. These are the results of DELETE FROM customers WHERE id = 2; (Siti, owner of orders 3 and 4) in real SQLite, for each ON DELETE choice:

ON DELETE Result of the DELETE Orders 3 and 4
CASCADE succeeds deleted too
SET NULL succeeds kept, customer_id becomes NULL
RESTRICT refused: FOREIGN KEY constraint failed kept, and so is Siti
NO ACTION (the default when nothing is written) refused: FOREIGN KEY constraint failed kept, and so is Siti

With SET NULL, Siti's orders stay, without an owner.

For a shop's orders, CASCADE from customers is almost always wrong: deleting a customer would also delete sales records and the accounts. Pick RESTRICT or SET NULL.

In Laravel: foreignId()->constrained()

A Laravel migration (a PHP file that creates and changes tables) writes the same foreign keys more briefly:

$table->foreignId('customer_id')->constrained();                          // REFERENCES customers(id)
$table->foreignId('order_id')->constrained()->cascadeOnDelete();           // ON DELETE CASCADE
$table->foreignId('author_id')->nullable()->constrained('users')->nullOnDelete(); // ON DELETE SET NULL
$table->foreignId('department_id')->constrained()->restrictOnDelete();     // ON DELETE RESTRICT

⚠️ Delete rules that stay silent, fail, or go too far

TL;DR: Primary key = a unique column that can't be NULL (empty), so one row can be pointed at for certain. Its kinds: auto-increment (a number the database fills in), UUID (a long code that is practically never the same twice), natural key (a real-world value) or composite key (a combination of columns). Pick a value that never changes. Foreign key = a column that points at another table's primary key. The database refuses a pointer to a row that doesn't exist (the error FOREIGN KEY constraint failed; in SQLite only after PRAGMA foreign_keys = ON). ON DELETE decides what happens to the child rows (orders) when their parent row (the customer) is deleted: CASCADE deletes them too, SET NULL empties the pointer, RESTRICT refuses, NO ACTION (the default) refuses as well. In a Laravel migration (a PHP file that creates tables): $table->foreignId('customer_id')->constrained(), plus cascadeOnDelete(), nullOnDelete() or restrictOnDelete().

⚡ Primary key: every row's ID card

Write:

INSERT INTO customers (id, name) VALUES (2, 'Rina');
-- UNIQUE constraint failed: customers.id

Meaning: A primary key is the identity number of each row: unique and never NULL (empty), so one row can be pointed at for certain. Siti already uses id 2 in customers, so SQLite refuses Rina's row with the error on the -- line. Pick a value that never changes, like an auto-increment id (a number the database fills in).

⚡ Foreign key: a pointer to another table

Write:

INSERT INTO orders (customer_id, total) VALUES (9, 500);
-- FOREIGN KEY constraint failed

Meaning: A foreign key links tables by pointing at another table's primary key. Here orders.customer_id points at customers.id. Customer 9 isn't in customers, so the order is refused. In SQLite, this check only runs after PRAGMA foreign_keys = ON;.

⚡ ON DELETE: what happens to the children

Guess first: ON DELETE on a foreign key decides what happens to the orders when their customer is deleted. Siti is deleted from customers. With ON DELETE SET NULL, what happens to her orders?

They stay, but their customer_id becomes NULL: orders without an owner.

Meaning: When a parent row (the customer) is deleted, CASCADE deletes the child rows (her orders) too, SET NULL empties their pointer, and RESTRICT and NO ACTION (the default when nothing is written) refuse the delete.

In the exercise, your function returns exactly "CASCADE", "SET NULL", "RESTRICT" or "NO ACTION", all uppercase.

What you will learn