check constraint in MySQL
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.
ALTER TABLE users ADD COLUMN age INT, 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.
CREATE TABLE users ( id INT PRIMARY KEY, 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.
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.
Random Code Snippet Queries: Sql
- Get comma separated ids from table using MySQL
- How to check column exists or not in table using MySQL
- How to show database tables in mysql using command line
- Create column after a column in existing table using query in MySQL
- SQL query to delete records older than 6 months
- Insert multiple rows in a single MySQL query
- Change existing MySQL table column id to autoincrement
- How to retrieve data from two tables with one SQL statement
- Database connection using mySQLi with object-oriented
- Drop foreign id column (user_id) in MySQL
- Get create table Query from existing table in phpMyAdmin
- SQL query to delete all rows older than 30 days
- How to check the MySQL version
- MySQL create procedure example
- Get data in random order with limit from table using mysql
- SQLSTATE: Warning: 1265 Data truncated for column 'visibility' at row 1
- Cannot drop index 'fk_role_id': needed in a foreign key constraint
- 1553 Cannot drop index 'posts_user_id_foreign': needed in a foreign key constraint
- How to create a new table from existing table in SQL