Skip to content

Unique Key

In one line

A unique key is a constraint that prevents duplicate values in a column — every value must be different.

In simple words

A unique key ensures that no two rows in a table have the same value in the constrained column (or combination of columns). This is useful for things like email addresses, usernames, or product codes — values that should never be duplicated.

A primary key is always unique, but a table can have multiple unique keys in addition to the primary key. For example, a users table might have id as the primary key and email as a unique key — both are unique, but id is the primary identifier.

Unlike a primary key, a unique key can technically allow NULL values (depending on the DBMS), and you can have many unique keys per table.

Example

sql
CREATE TABLE users (
  id       SERIAL PRIMARY KEY,
  email    TEXT UNIQUE NOT NULL,
  username TEXT UNIQUE NOT NULL
);
-- Both email and username must be unique

The UNIQUE constraint prevents two users from registering with the same email or username.

Common confusions

  • Confused with: primary key

    The difference: A primary key is the main identifier and cannot be NULL; a unique key just prevents duplicates and you can have several per table.

Related terms

Related Resources

Related Lessons

  • Constraints

    Learn about unique keys and other constraints.

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary