Beginner Topic 5 of 51 Databases
Primary Keys
Column that uniquely identifies each row.
How it works
A primary key is a column or set of columns whose values uniquely identify each row in a table; it cannot be NULL and cannot repeat. The database builds a unique index on it to enforce uniqueness and speed up lookup. Keys can be natural, drawn from real-world data such as an email address, or surrogate, such as an auto-increment integer or UUID with no business meaning. Composite keys use multiple columns.
Step-by-step walkthrough
- A primary key column identifies each row.
- Values must be unique.
- Inserting a second id 3 is rejected.
- The key can never be NULL.
- Other tables point to a row through its key.
Where it is used
Every table should have one so rows can be referenced by other tables through foreign keys and updated or deleted precisely. ORMs and replication tools depend on them.
Common pitfall
Natural keys can change, such as a renamed username, forcing cascading updates; surrogate keys avoid this. Sequential IDs expose counts and are guessable, while random UUIDs fragment indexes. Choosing very wide keys inflates every index and foreign key. Never reuse a key for a different entity.
Where it fits in the course
Primary Keys is topic 5 of 51 in Databases, rated Beginner. It follows Tables, Rows and Columns. The next topic is Foreign Keys.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Databases quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Databases quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Primary Keys?
Where do people use Primary Keys?
What is the most common mistake with Primary Keys?
What should I learn before this topic?
How can I practice it?
Is Primary Keys hard to learn?
How long does it take to learn Primary Keys?
Which topics are related to Primary Keys?
What should I study after Primary Keys?
Related topics
- Tables, Rows and Columns (Databases)
- Foreign Keys (Databases)
- Relational Model (Databases)
- SQL Basics (Databases)
- SSH Keys (DevOps & Tooling)