Sobes.tech
Junior — Middle

How does creating a unique index differ from defining a primary key in a database?

sobes.tech AI

Answer from AI

A Primary Key is a constraint that uniquely identifies each record in a table. It automatically implies uniqueness and does not allow NULL values. There can only be one primary key in a table.

A Unique Index ensures the uniqueness of values in one or more columns, but unlike a primary key, it can allow NULL values (depending on the DBMS), and there can be multiple unique indexes in a table.

Main differences:

  • Primary Key — unique, does not allow NULL, one per table, serves as the main identifier.
  • Unique Index — ensures uniqueness, can allow NULL, multiple per table, used to ensure data uniqueness but not necessarily for identification.

Example of creating a primary key and a unique index in SQL:

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

Here, id is the primary key, and email is a unique index.