check constraint in MySQL

Created at 20-May-2023 , By samar

Check Constraint in MySQL Allows you to define custom conditions that must be satisfied by the column values.

Add Check constraint to existing table (users) of MySQL

Heer we have a MySQL query to modify the existing users table to add the check constraint for age column.

ADD CONSTRAINT CHK_AGE CHECK (age >= 18 AND age <= 65);

Add check constraint to age column while creating users table

You can also create a check constraint for age column to restrict the value for age column between 18 to 65 while creating the users table in MySQL.

 age INT,
 CONSTRAINT CHK_AGE CHECK (age <= 18 AND age >= 65)

The above given SQL query creates a table named "users" with two columns: "id" and "age". The "id" column is defined as an integer primary key, which means it uniquely identifies each row in the table. The "age" column is also defined as an integer.

Additionally, a CHECK constraint named "check_age" is added to the "age" column. This constraint ensures that the value in the "age" column falls within the range of 18 to 65 (inclusive). In other words, any value inserted or updated in the "age" column must satisfy the condition (age <= 18 and age >= 65). This constraint helps enforce data integrity by ensuring that only valid age values are allowed in the table.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.