Adding CHECK Constraints to an Existing Table
We are going to add a CHECK constraint to our existing table. As our table have no check constraint, we add one with the below query.
Query:
ALTER TABLE w3wiki
ADD CONSTRAINT CHK_validEntry
CHECK (rank < 500);
Now if we try to enter any row with rank grater than 500 will throw us an error.
Query:
INSERT INTO w3wiki(id,name,questions,rank)
VALUES(06,'Harsh',150,560);
Output:
Explanation: In the above image, we can clearly notice an error. This is due to our newly imposed check constraint condition i.e. rank should be less than 500. We can clearly see that we are trying to enter a new row with rank as ‘560’ which is clearly not following our condition.
MYSQL CHECK Constraint
MySQL is a very famous and widely used open-source RDBMS. It is used to store, retrieve, and manage structured data efficiently. It is used in both types of applications i.e. large and small scale applications. In MySQL, the CHECK constraint enforces a condition on the column(s) of a table. It makes sure that a specific type of data only gets inserted into the table.
In this article, we are going to explore various use cases of MYSQL check constraints. We are going to cover all the basic points with clear and concise examples along with their explanations.