SQL Server Interview Question #31

What is a UNIQUE constraint?

Data Types, Keys & Constraints Junior Beginner

Detailed Explanation

A UNIQUE constraint enforces uniqueness for the specified column or combination of columns. It is useful for candidate keys such as usernames, email addresses, codes, or SKUs.

Unlike a primary key, a table can have multiple UNIQUE constraints. SQL Server implements uniqueness through a unique index.

NULL behavior is also important: for a normal single-column UNIQUE constraint in SQL Server, only one NULL value is permitted.

Code Example

CREATE TABLE Products
(
    Id INT IDENTITY PRIMARY KEY,
    SKU NVARCHAR(50) NOT NULL,
    Name NVARCHAR(200) NOT NULL,
    CONSTRAINT UQ_Products_SKU UNIQUE (SKU)
);