'Check Constraint' is used to check for a rule being enforced on one or more columns in a table.
Check Constraint
The 'Check Constraint' used to restrict the values being entered in a column. Say for example you can use this
constraint to ensure in a gender column, the values being entered is either 'M' or 'F'.
Any other value being entered will prevent the whole record from being entered into the table.
SQL 'Check Constraint' Syntax
CREATE Table tablename
(
column1 datatype PRIMARY KEY,
column2 datatype,
column3 datatype,
column4 datatype,
.
.
.
columnn datatype
CONSTRAINT constraintname CHECK (columnname and condition)
)
The above method of creating a table creates an 'Check' constraint on column at the table level
is shown.
The Check Constraint Example
CREATE TABLE Employees
(
EmployeeID smallint PRIMARY KEY,
EmployeeName nvarchar(50) NOT NULL,
DateOfBirth smalldatetime NOT NULL,
DesignationID smallint NULL,
DeptID smallint NULL,
PhoneNo nvarchar(12) NULL,
City nvarchar(50) NOT NULL,
Salary decimal(5, 2) CHECK (Salary >= 450)
)
Note: When creating the columns, the data type of the column must be given so that you know what datatype it holds.
If it's a non integer, you need to specify the length of the column also. Here we are ensuring that when a new employee is being added or an
existing employee's record is being updated, their salary will be >= $450.