Database.What is a “primary key”? What are the criteria for choosing one?

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:

  1. Uniqueness
    • It must uniquely identify every row in the table.
  2. Non-nullability
    • It must never be NULL (every row must have a value for the key).
  3. Immutability
    • The value should rarely or never change. Changing primary key values can break relationships.
  4. Minimality
    • Use as few columns as possible (prefer simple over composite keys if possible).
  5. 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
This entry was posted in Без рубрики. Bookmark the permalink.