Codacoda
Back to Academy

relational database

Primary & Foreign Keys

A primary key uniquely identifies each row in a table — no two rows can share the same primary key. A foreign key is a column in one table that references the primary key of another table, creating a relationship between them. Together, they enforce referential integrity: you cannot reference a row that does not exist.

Use Cases

  • Linking orders to customers so every order belongs to a valid customer
  • Connecting blog posts to authors to enforce that each post has a real author
  • Preventing orphaned records when parent rows are deleted
  • Building one-to-many relationships like departments and employees

Visualization

BEFOREFK → PKusersid (PK)name1Alice2Bobordersid (PK)user_id (FK)item
Speed:1x
Two tables: users (PK: id) and orders (FK: user_id)Step 1 / 6

Implementation

Output

Click "Run Code" to see output...