A primary key is a column or a set of columns in a table that uniquely identifies each row.
It ensures that:
- No two rows have the same value in the primary key.
- The key value is never NULL.
✅ Example:
CREATE TABLE Customers (
customer_id INT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
Here, customer_id
is the primary key, ensuring each customer has a unique identifier.
📌 Criteria for Choosing a Primary Key:
- Uniqueness
- It must uniquely identify every row in the table.
- Non-nullability
- It must never be NULL (every row must have a value for the key).
- Immutability
- The value should rarely or never change. Changing primary key values can break relationships.
- Minimality
- Use as few columns as possible (prefer simple over composite keys if possible).
- Stability and simplicity
- Prefer short, numeric keys (like integers or UUIDs) over long text fields (like email or names).
🚫 Bad Choices for Primary Keys:
- Names (can change and are not unique)
- Emails (can change, even though often unique)
- Phone numbers (can change)
- Composite keys when a surrogate key would do better