| SQL training| SQL Tutorial for beginners| Intellipaat
UNIQUE Constraint in SQL Server:
When you want a column or columns not to accept any duplicate values, then you need to apply UNIQUE Constraint to that column or columns. That means the UNIQUE constraint is used to avoid duplicate values but it accepts a single NULL value in that column.
A table can contain any number of UNIQUE constraints. We can apply the UNIQUE constraint on any data type column such as integer, character, money, etc.
Example:
CREATE TABLE Customer
(
Id INT UNIQUE,
NAME VARCHAR(30) UNIQUE,
Emailid VARCHAR(100) UNIQUE
)
INSERT customer VALUES (NULL, NULL, NULL)--ALLOWED
INSERT customer VALUES (11, 'BB', '[email protected]')--ALLOWED
INSERT customer VALUES (NULL, NULL, NULL) -- NOT ALLOWED
Check Constraint in SQL Server:
The Check Constraint is used to enforce domain integrity. Domain integrity ensures that the values going to store in a column must follow some defined rules such as range, type, and format.
In simple words, we can say that the Domain Integrity constraint enforces the valid entries for a given column value by restricting the type of the value, the format of the data, or the range of possible values.
CREATE TABLE Employee
We need to use the Check Constraints in the SQL server to limit the range of possible values of a column.
The check constraints can be created at two different levels
Column-Level Check Constraints: When we create the check constraints at the column level then they are applied only to that column of the table.
Table-level Check Constraints: When we create the check constraints at the table level, then it can be referred from any column within that table.