Open In App

SQL | CHECK Constraint

SQL Constraints Check Constraint is used to specify a predicate that every tuple must satisfy in a given relation. It limits the values that a column can hold in a relation.

Syntax:



CREATE TABLE pets(
        ID INT NOT NULL,
        Name VARCHAR(30) NOT NULL,
        Breed VARCHAR(20) NOT NULL,
        Age INT,
        GENDER VARCHAR(9),
        PRIMARY KEY(ID),
        check(GENDER in ('Male', 'Female', 'Unknown'))
        );

Note: The check constraint in the above SQL command restricts the GENDER to belong to only the categories specified. If a new tuple is added or an existing tuple in the relation is updated with a GENDER that doesn’t belong to any of the three categories mentioned, then the corresponding database update is aborted.

Query



Constraint: Only students with age >= 17 are can enroll themselves in a university. Schema for student database in university:

CREATE TABLE student(
        StudentID INT NOT NULL,
        Name VARCHAR(30) NOT NULL,
        Age INT NOT NULL,
        GENDER VARCHAR(9),
        PRIMARY KEY(ID),
        check(Age >= 17)
        );

Student relation:

StudentID Name Age Gender
1001 Ron 18 Male
1002 Sam 17 Male
1003 Georgia 17 Female
1004 Erik 19 Unknown
1005 Christine 17 Female

Explanation: In the above relation, the age of all students is greater than equal to 17 years, according to the constraint mentioned in the check statement in the schema of the relation. If, however following SQL statement is executed:

INSERT INTO student(STUDENTID, NAME, AGE, GENDER) 
VALUES (1006, 'Emma', 16, 'Female');

There won’t be any database update and as the age < 17 years. Different options to use Check constraint: 

alter table TABLE_NAME modify COLUMN_NAME check(Predicate);
alter table TABLE_NAME add constraint CHECK_CONST check (Predicate);
alter table TABLE_NAME drop constraint CHECK_CONSTRAINT_NAME;
alter table TABLE_NAME drop check CHECK_CONSTRAINT_NAME;

View existing constraints on a particular table

If you want to check if a constraint or any constraint exists within the table in mysql then you can use the following command. This command will show a tabular output of all the constraint-related data for the table name you’ve passed in the statement, in our case we’ll use the employee table.

SELECT * 
FROM information_schema.table_constraints 
WHERE table_schema = schema() 
AND table_name = 'employee';
Article Tags :