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:

rank > 500

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.

Similar Reads

MYSQL CHECK Constraint

In MYSQL, the Check constraint is used to impose conditions on what type of data to be inserted into our table. It helps in maintaining the accuracy and consistency of the data. It helps in avoiding the entry of data that does not follow our specified conditions....

Creating a table with CHECK Constraint

In this, we are heading to create a table in our database. We will create a table named ‘geeksforgeeks‘. We will apply a check constraint on two of its columns....

Examples of CHECK Constraints

In this, we are going to explore how check constraint actually works in MYSQL. We will see how it will behave if have try to enter any records which do not follow its imposed condition....

Drop the CHECK constraint

In order to drop CHECK constraint from our existing table, we will be using ALTER and DROP clause. ALTER Clause is used to modify the structure of the table and DROP Clause is used remove a database object....

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....

Conclusion

Overall, check constraint is use to impose a condition on the data which are going to be inserted into our table. We can clearly prevent on adding irrelevant data to our table. We have seen many examples related to check constraints, how to remove check constraint from existing table and adding check constraint to the existing table. Now you can write all the queries related to check constraint with ease can can get the desired output....