SQL Unique Statement
The Unique constraint statement ensures that all values in a column are different. Both the Unique and Primary Key constraints provide a guarantee for uniqueness for a column or set of columns. A Primary key constraint automatically has a unique constraint in SQL. However, you can have many unique constraints per table, but only one primary key constraint per table.
SQL Server Unique constraints allow you to ensure that the data stored in a column, or a group of columns, is unique among the rows in a table.
Syntax
- CREATE TABLE EmployeeName (
- EmpID int NOT NULL UNIQUE,
- EmpName varchar(255) NOT NULL,
- );
The above query creates a table with the name "EmployeeName" and column name EmpID which is both Not Null and Unique(i.e we cannot have empty or duplicate data) and EmpName
Using Unique constraint on create table statement
Syntax
- CREATE TABLE Employee (
- EmpID int NOT NULL UNIQUE,
- EmpName varchar(255) NOT NULL,
- EmpFirstName varchar(255),
- EmpLastname varchar(255),
- EmpAge int
- );
The above query created a table with the name "Employee" and the first column name EmpId is Not NULL and UNIQUE, other column name EmpName,EmpFirstName,EmpLastname, EmpAge
Using Unique constraint on alter table
Syntax
- ALTER TABLE Employee
- ADD UNIQUE (EmpID);
The above query with add a column EmpID and make it UNIQUE.
"Unique" is used to signify a Unique constraint, and also to define a unique name a Unique constraint,on multiple columns.
Syntax
- ALTER TABLE Employee
- ADD CONSTRAINT UC_Employee UNIQUE (EmpID,EmpLastName);
The above query will add EmpID and EmpLastName columns into the UC_Employee table, with the Unique Constraint
Using Drop a Unique constraint statement
Use the following example to drop a Unique constraint:
Syntax
- ALTER TABLE Employee
- DROP CONSTRAINT UC_Employee;
The above query will remove the "Unique" Constrain from the Employee table.
Using SQL Server Management Studio in Unique Constraint
To create a unique constraint statement:
-
In Object Explorer, right-click the table to which you want to add a unique constraint, and click Design.
-
On the Table Designer menu, click Indexes/Keys.
-
In the Indexes/Keys dialog box, click Add.
-
In the grid under General, click Type and choose Unique Key from the drop-down list box to the right of the property.
-
On the File menu, click Save table name.

Join the conversation! Your thoughts help the community grow.