Home / Learn Secure SQL / Primary and Foreign Keys
Primary and Foreign Keys
Uniquely identifying rows, and linking tables correctly.
The gistUniquely identifying rows, and linking tables correctly.
The idea, explained simply
Definition
A primary key uniquely identifies each row in a table; a foreign key points to a primary key in another table, enforcing that the referenced row actually exists.
Why you need this
Keys are the backbone that makes joins meaningful and prevents "orphan" rows pointing nowhere.
How it works
Give every table a primary key (usually an auto-incrementing id), and declare foreign keys explicitly so the database enforces them.
Where you'll see this
- Web application code review
- Backend development
- Database administration
Foreign key enforcement (expected error)SQL: edit and run
This fails on purpose: user 999 does not exist, and the foreign key constraint refuses the orphan row.
Test what you just read
1. A foreign key constraint prevents...
Orphan references.