A Checklist Before Choosing a Primary Key
Every table needs a primary key, and changing it later is a chore. Before you decide, run through these checks. Each comes with a short reason, so you can explain your choice to a teacher, a reviewer or your future self.
The four must-haves
- [ ] Unique in every case. No two rows may ever share it, not even in rare situations like twins with the same name.
- [ ] Always present. A primary key can never be empty, so every row must have a value from the moment it is created.
- [ ] Stable. It should never need to change, because other tables point to it.
- [ ] Not sensitive. It will be copied into other tables, URLs and logs, so it must not be private information like an ID card number.
If you are considering a "natural" value
A natural key is a real-world value, such as an email address or a product code.
- [ ] Could it change? People change emails; companies renumber products.
- [ ] Could it be missing? A new customer might not have an email yet.
- [ ] Is it the same length and format every time? Mixed formats cause matching problems.
- [ ] Is it controlled by someone else? If an outside organisation can change it, you cannot guarantee it stays stable.
If any answer worries you, use a generated id instead and keep the natural value as an ordinary column with a UNIQUE rule.
If you are using a generated id
A surrogate key is a value the database creates, such as 1, 2, 3, which means nothing outside the database.
- [ ] Let the database generate it. Use your database's auto-numbering feature, such as
INTEGER PRIMARY KEYin SQLite or an identity column in PostgreSQL. - [ ] Do not reuse numbers. Deleted ids should stay retired to avoid confusing old references.
- [ ] Do not give the number meaning. "Ids over 1000 are VIP customers" is a rule that will break.
If the key is made of two columns
- [ ] Is the pair truly unique? In a linking table like
enrolments(student_id, course_id), it often is. - [ ] Will other tables need to point at these rows? If yes, a single id may be simpler for them.
How other tables will use it
- [ ] Decide the foreign key column names. A common habit is
<table>_id, such asstudent_id. - [ ] Use the same type everywhere. If
students.idis an INTEGER,enrolments.student_idshould be an INTEGER too. - [ ] Think about deletes. If a row is deleted, what should happen to rows that point to it?
Before you finish
- [ ] Write one sentence explaining your choice. Our primary key decision template gives you a format.
- [ ] Insert a few test rows, including an awkward one, to see whether the key holds up.
For practice, try the eight primary key scenarios.
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.