SQL CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a column it will allow only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.
SQL CHECK on CREATE TABLE
The following SQL creates a CHECK constraint on the "Age" column when the "student" table is created. The CHECK constraint ensures that the age of a person must be 18, or older:
Example
MySQL CREATE TABLE student( id int NOT NULL , Last_name varchar( 50 ) NOT NULL , First_name varchar( 50 ) , Age int,You can click on above box to edit the code and run again.
CHECK (Age>= 18 ) );
Example
SQL Server / Oracle / MS Access:You can click on above box to edit the code and run again.
CREATE TABLE student( id int NOT NULL , Last_name varchar( 50 ) NOT NULL , First_name varchar( 50 ) , Age int CHECK (Age>= 18 ) );
Example
MySQL / SQL Server / Oracle / MS Access: CREATE TABLE student ( id int NOT NULL , Last_name varchar( 50 ) NOT NULL , First_name varchar( 50 ) , Age int,You can click on above box to edit the code and run again.
City varchar( 50 ), CONSTRAINT CHK_student CHECK(Age>=18 AND City='Ranchi') );
SQL CHECK on ALTER TABLE
To create a CHECK constraint on the "Age" column when the table is already created, use the following SQL:
Example
MySQL / SQL Server / Oracle / MS Access:You can click on above box to edit the code and run again.
ALTER TABLE student
ADD CHECK (Age>=18 ;
Example
MySQL / SQL Server / Oracle / MS Access:You can click on above box to edit the code and run again.
ALTER TABLE student
ADD CONSTRAINT CHK_studentAge CHECK (Age>=18 AND City='Ranchi');