MODULE 05 · DATABASE & SQL

Foreign Key

A key that references a key in another table and helps enforce a relationship between tables.

01 · What is it?

A foreign key references a key in another table and helps enforce a relationship between tables.

It usually stores a value that points to a primary key in a related table.

Simple Definition: A foreign key is a link from one table to another.

02 · Think of it like…

Think of a foreign key as a label on an order that says which customer owns it.

The customer keeps the identity. The order keeps the reference.

Customers
id = 42
orders.customer_id
= 42
The order belongs to Customer 42

03 · What does it do?

A foreign key helps a database:

Connect Tables

Point a row in one table to a row in another.

Protect References

Prevent links to records that do not exist.

Keep Data Consistent

Make related records agree about their connections.

Support Joins

Give SQL a reliable path for combining related data.

04 · Where is it used?

Foreign keys are used wherever one kind of record belongs to another.

Orders → Customers

Each order points to the customer who placed it.

Reviews → Products

Each review points to the product being reviewed.

Comments → Posts

Each comment points to the post it belongs to.

Employees → Departments

Each employee can point to a department.

05 · Example

An orders table can store the customer relationship directly in the row.

CREATE TABLE orders (
  id INTEGER PRIMARY KEY,
  customer_id INTEGER,
  FOREIGN KEY (customer_id)
    REFERENCES customers(id)
);

orders.customer_id is the foreign key.

customers.id is the referenced key.

The database can reject an order that points to a customer that does not exist.

06 · How it connects

FrontendAPIBackendSQLorders.customer_idcustomers.id

The foreign key gives a query a safe, meaningful connection between child and parent rows.

07 · Do Not Confuse

Foreign Key

Points from a row in one table to a key in another table.

Primary Key

Uniquely identifies a row inside its own table.

A primary key identifies the record. A foreign key identifies the record it is related to.

09 · What to Remember

A foreign key connects a row to a key in another table.

It helps the database protect relationships and keep related data consistent.

In a common one-to-many relationship, the child table stores the foreign key.

Parent Primary KeyChild Foreign Key
↑