Back to results for “Constraints (Primary Key”
SQL Server › Constraints (Primary Key, Foreign Key, Check & Unique)

How is a unique constraint different from a primary key constraint, and when would you use one instead of the other?

Intermediate

Answer

A unique constraint, like a primary key, ensures every value in a column is distinct, but unlike a primary key it does allow a single NULL value and a table can have multiple unique constraints, making it useful for enforcing uniqueness on columns like an email address that are not the table's main identifying key.
CREATE TABLE Customers (
  CustomerId INT PRIMARY KEY,
  Email VARCHAR(255) UNIQUE
);
Real-world example A customer database uses a unique constraint on the email column to prevent duplicate customer accounts from being created with the same email address, while still using CustomerId as the actual primary key.

Common follow-ups: How many unique constraints can a single table have?;Does a unique constraint automatically create an index behind the scenes?