Sobes.tech
Middle+

What is the difference between Primary Key and Unique Key?

sobes.tech AI

Answer from AI

Primary Key is a unique identifier for a record in a table that cannot contain NULL and guarantees the uniqueness of each row. There can only be one Primary Key in a table.

Unique Key also ensures the uniqueness of values in a column or set of columns but allows NULLs (depending on the DBMS, sometimes multiple NULLs are considered unique). A table can have multiple Unique Keys.

Main differences:

  • Primary Key — one only, Unique Key — can be multiple.
  • Primary Key does not allow NULL, Unique Key can.
  • Primary Key is automatically indexed, Unique Key is too, but with some implementation differences.

Example in SQL:

CREATE TABLE users (
  id INT PRIMARY KEY,
  email VARCHAR(255) UNIQUE
);