Sql Server

SQL | Unique Key Constraint

SQL | Unique Key Constraint

SQL | Unique Key Constraint

Constraints are used to specify the rules concerning data in the table. It can be applied for single or multiple fields in an SQL table during the creation of the table or after creating using the ALTER TABLE command.

Unique Key Constraint

Unique Key constraints also identify an individual tuple uniquely in a relation or table. A table can have more than one unique key, unlike a primary key.
Unique key constraints can accept only one NULL value for the column. Unique constraints are also referenced by the foreign key of another table
It can be used when someone wants to enforce unique constraints on a column and a group of columns which is not a primary key.

Features of Unique Key
1. There can be more than one unique key for a table.
2. Unique Keys have the liberty of having NULL values in the column.
3. Unique Keys can be formed from one or more columns.
4. Foreign Keys can refer to Unique Keys for referencing.

Create A Unique Key on New Table

CONSTRAINT <constraint_name> UNIQE(<column_name>)  

    EmployeeID int,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int
    PhoneNo varchar(15),
    ADD CONSTRAINT UNQ_Emp_Phone Unique(PhoneNo)

-- Adds a unique constraint on the PhoneNo column of the existing Employee table.

Add Unique Constraint in Existing Table

ALTER TABLE Employee  
ADD CONSTRAINT UNQ_Emp_Phone Unique(PhoneNo)

Differences between the primary key and unique key in SQL Server?
Both unique key and Primary Key handles the uniqueness of a column on which they are applied. But,
1. By default in SQL Server the primary key creates a unique clustered index whereas the unique key creates a unique non-clustered index on the column.
2. The primary key column doesn’t allow NULL values whereas the unique key column allows only one NULL value.

Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.