Curriculum
Course: SQL
Login

Curriculum

SQL

SQL References

0/80

MySQL Functions

0/139

SQL Server Functions

0/84

SQL Quick Ref

0/1
Text lesson

CHECK

CHECK

The CHECK constraint restricts the permissible values that can be inserted into a column within a database table.

SQL CHECK on CREATE TABLE

The provided SQL establishes a CHECK constraint on the “Age” column during the creation of the “Persons” table. This constraint guarantees that no person under the age of 18 can be added.

MySQL:

CREATE TABLE Persons (
    Age int,
    CHECK (Age>=18)
); 

SQL Server / Oracle / MS Access:

CREATE TABLE Persons (
    Age int CHECK (Age>=18)
); 

For the ability to assign a specific name to a CHECK constraint and to define such a constraint across multiple columns, adhere to the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons (
    Age int,
    City varchar(255),
    CONSTRAINT CHK_Person CHECK (Age>=18 AND City=‘Sandnes’)
); 

SQL CHECK on ALTER TABLE

For creating a CHECK constraint on the “Age” column after the table has been created, utilize the following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons
ADD CHECK (Age>=18); 

For enabling the naming of a CHECK constraint and defining it across multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City=‘Sandnes’); 

DROP a CHECK Constraint

To remove a CHECK constraint, employ the following SQL:

SQL Server / Oracle / MS Access:

ALTER TABLE Persons
DROP CONSTRAINT CHK_PersonAge; 

MySQL:

ALTER TABLE Persons
DROP CHECK CHK_PersonAge;