How is a unique constraint different from a primary key constraint, and when would you use one instead of the other?
Short 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…
Advertisement
AModel 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.
Likely follow-ups
- How many unique constraints can a single table have?
- Does a unique constraint automatically create an index behind the scenes?
Related topics