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')
)
- Easy to use with a learn-by-doing approach
- Offers quality content
- Gamified in-browser coding experience
- The price matches the quality
- Suitable for learners ranging from beginner to advanced
- Free certificates of completion
- Focused on data science skills
- Flexible learning timetable
- Simplistic design (no unnecessary information)
- High-quality courses (even the free ones)
- Variety of features
- Nanodegree programs
- Suitable for enterprises
- Paid Certificates of completion
- A wide range of learning programs
- University-level courses
- Easy to navigate
- Verified certificates
- Free learning track available
- University-level courses
- Suitable for enterprises
- Verified certificates of completion
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;