Constraints or validations are a well known phenomenon in and Database
Management system to ensure that the columns can receive values that are well
within the limit and restrictions imposed. For e.g. we can impose a check on a
column named “Age” that the value should be between 20 – 40 only. This can be
achieved by the following constraint
Create
Table EmpTemp
(
Age
numeric(10) constraint age_check check (age between 20 and 40)
)
There are different kinds of constraints in SQL Server:
A PRIMARY
KEY CONSTRAINT
This constraint is to ensure that we can differentiate between two rows
in a table. There can only be one primary key in a table and it cannot be null
and it will not allow duplicate values.
Create
Table EmpTemp
(
Code numeric(10) constraint pk_primary
primary key
)
B. UNIQUE
This constraint is to ensure that we are not going to insert a duplicate
value.
Create Table EmpTemp
(
Code numeric(10) constraint uc_constraint unique
)
C. NOT
NULL
This constraint is to that the column is not going
to accept null values.
Create Table EmpTemp(
Code numeric(10) constraint uc not null
)
D. Check
This constraint is to ensure that the columns are going to check for
specific values or values within ranges.
Create Table EmpTemp
(
Code numeric(10) constraint check1 check (code between 2000 and 5000),
Job varchar(20) constraint check2 check (job in ('MANAGER','ANALYST'))
)
Comments