Grab the chance to earn a scholarship!

Study a desired course for free & get money

Code has been added to clipboard!

Using SQL CHECK on Different Database Systems

Reading time 2 min
Published Aug 9, 2017
Updated Oct 11, 2019

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:

Example
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:

Example
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:

Example
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')
)
Theory is great, but we recommend digging deeper!

CHECK ALTER TABLE

When creating a constraint CHECK after a table is produced:

MS Access / SQL Server / Oracle / MySQL:

Example
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:

Example
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:

Example
ALTER TABLE Person
DROP CONSTRAINT ck_Person

MySQL:

Example
ALTER TABLE Person
DROP CHECK CK_PersonsAge;