Contents
SQL CHECK Constraint: Main Tips
- This constraint is needed in order to cap the range of values that could be in the column.
- When defining the constraint to a sole column it permits just specific values to that column.
- When defining the constraint to a table it will cap the values of specific columns by basing off the values of different columns in the same row.
CHECK CREATE TABLE
The code examples below produce a constraint CHECK in the "Person" table on the column "P_Ids". The constraint defines that the column can only have integers bigger than 0.
MySQL:
CREATE TABLE Person
(
P_Ids int NOT NULL,
LName varchar(255) NOT NULL,
FName varchar(255),
AddressID varchar(255),
CityID varchar(255),
CHECK (P_Ids>0)
)
MS Access / SQL Server / Oracle:
CREATE TABLE Person
(
P_Ids int NOT NULL CHECK (P_Ids>),
LName varchar(255) NOT NULL,
FName varchar(255),
AddressID varchar(255),
CityID varchar(255)
)
In order to be able to name the constraint CHECK, and defining it on various columns, the example below shows the syntax:
MS Access / SQL Server / Oracle / MySQL:
CREATE TABLE Person
(
P_Ids int NOT NULL,
LName varchar(255) NOT NULL,
FName varchar(255),
AddressID varchar(255),
CityID varchar(255),
CONSTRAINT ck_Person CHECK (P_Ids>0 AND CityID='paris')
)
CHECK ALTER TABLE
When creating a constraint CHECK after a table is produced:
MS Access / SQL Server / Oracle / MySQL:
ALTER TABLE Person
ADD CHECK (P_Ids>0)
In order to be able to name the constraint CHECK, and defining it on various columns, the example below shows the syntax:
MS Access / SQL Server / MySQL / Oracle:
ALTER TABLE Person
ADD CONSTRAINT ck_Person CHECK (P_Ids>0 AND CityID='Paris')
DROP CHECK: Example
The code examples below show how to drop the constraint CHECK:
SQL Server / MS Access / Oracle:
ALTER TABLE Person
DROP CONSTRAINT ck_Person
MySQL:
ALTER TABLE Person
DROP CHECK CK_PersonsAge;