Primary Keys: The Unique ID for Every Row
A primary key is like a social security number for a database row, uniquely identifying it. It's used to reliably fetch records and link related data across tables. The footgun is using a natural key, like an email address, that might change over time.
WHY IT EXISTS: Databases need a foolproof way to distinguish one row from another. Without a unique identifier, you could not reliably update 'John Smith's' record if there were two, or know which user placed which order. A primary key solves this by enforcing uniqueness for every single record.
THE MENTAL MODEL: Think of a primary key as the license plate on a car. While many cars might be a 'blue 2022 Honda Civic', only one can have the license plate 'XYZ-123'. This plate uniquely identifies that specific car, no matter what other attributes it shares with others. In a database, the primary key is that unique, unchanging identifier for a row.
HOW IT WORKS: When you declare a column (or set of columns) as a primary key, the database enforces two critical constraints. First, the value in that column must be unique across all rows in the table. Second, the value cannot be null (empty). This is most often an auto-incrementing integer (1, 2, 3...) or a universally unique identifier (UUID) that the database generates automatically for each new record.
WHEN TO USE IT: Every table in a relational database should have a primary key. It is the fundamental mechanism for creating relationships (foreign keys) between tables. For example, to link an 'Orders' table to a 'Customers' table, the 'Orders' table would include a 'customer_id' column that references the primary key of the 'Customers' table. It is also essential for any efficient data retrieval, update, or deletion operation.
WHEN NOT TO USE IT: The question is less about whether to use a primary key and more about what to use as the key. Avoid using 'natural' keys—attributes that exist in the real world, like email addresses or usernames. These can change, which creates a maintenance nightmare. If a user changes their email, you would have to update that value in every single table that references it. This is why 'surrogate' keys (like auto-incrementing integers or UUIDs) are almost always preferred.
ONE CANONICAL EXAMPLE: Consider a Users table with columns for UserID, Username, and Email. You would designate UserID as the primary key. Even if two users have the same name, or one user changes their email, their UserID (e.g., 1138) remains constant and unique. An Orders table could then have an Order_UserID column containing '1138' to unambiguously link an order to that specific user.
Read the original → en.wikipedia.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.