T-SQL Tutorial

UNIQUE constraint T-SQL


A UNIQUE constraint in SQL Server is a type of integrity constraint that ensures that the values in a specific column or set of columns are unique across all rows in a table. This means that no two rows can have the same values in the specified columns.

When you create a UNIQUE constraint, SQL Server will automatically create a unique index on the specified columns to enforce the constraint. This can help to improve the performance of queries that reference those columns and ensure the integrity of your data.


Example of UNIQUE constraint

The example below shows how to define a column with UNIQUE constraint when creating a table in SQL Server.

USE model;
GO
CREATE TABLE employee (
employee_id INT PRIMARY KEY,
name VARCHAR(200) NOT NULL,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(100) NOT NULL
);
GO

Add UNIQUE constraint

This SQL statement adds a UNIQUE constraint on the "Email" column of the "Employee" table, ensuring that no two records can have the same email address.

ALTER TABLE employee
ADD CONSTRAINT UQ_email UNIQUE (email);


You can also create a UNIQUE constraint across multiple columns, which means that the combination of values in those columns must be unique across all rows in the table. This can be useful for enforcing business rules or for creating relationships between tables.