The CHECK constraint restricts the range of values that can be inserted into a column.
When applied to a column, it enforces specific allowable values.
When applied to a table, it can restrict values in certain columns based on values in other columns within the same row.
This SQL statement establishes a CHECK constraint on the “Age” column during the creation of the “Persons” table. This constraint guarantees that a person’s age must be 18 or higher.
MySQL:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int, CHECK (Age>=18) ); |
SQL Server / Oracle / MS Access:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int CHECK (Age>=18) ); |
To enable the naming of a CHECK constraint and to define it across multiple columns, employ the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int, City varchar(255), CONSTRAINT CHK_Person CHECK (Age>=18 AND City=‘Sandnes’) ); |
If you need to establish a CHECK constraint on the “Age” column after the table has already been created, utilize the following SQL statement:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons ADD CHECK (Age>=18); |
To name a CHECK constraint and define it on multiple columns, utilize the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City=‘Sandnes’); |
To remove a CHECK constraint, employ the following SQL statement:
SQL Server / Oracle / MS Access:
ALTER TABLE Persons DROP CONSTRAINT CHK_PersonAge; |
MySQL:
ALTER TABLE Persons DROP CHECK CHK_PersonAge; |