UNIQUE Constraint

A UNIQUE constraint guarantees that every value in a column (or set of columns) is different across all rows. It prevents duplicate entries like two users with the same email.

SQL

Unlike a primary key, a UNIQUE column can usually contain a single NULL, and a table can have many unique columns but only one primary key.

The database automatically creates an index for a unique constraint, which also makes lookups on that column fast.

Syntax

CREATE TABLE table_name (
  column datatype UNIQUE
);

Examples

SQL

CREATE TABLE accounts (
  id INT PRIMARY KEY,
  username TEXT UNIQUE
);

Output:

Two accounts can't share a username.

Learn it in a lesson

See also

Back to the Dictionary