CHECK CONSTRAINT - (MySQL Misc)
In MySQL, a check constraint is a type of constraint that checks whether a given condition is satisfied by the columns in a table. In this tutorial, we'll discuss the syntax, example, output, explanation, use, important points, and summary of the check constraint in MySQL.
Syntax
The syntax for creating a check constraint in MySQL is as follows:
CREATE TABLE table_name (
column1 datatype CONSTRAINT constraint_name CHECK (condition),
column2 datatype,
...
);
The CHECK
keyword specifies the condition to be checked. If the condition is not satisfied, MySQL will not allow the data to be inserted or updated.
Example
Let's say we have a table called employees
and we want to add a check constraint that ensures that the salary of an employee is greater than or equal to 0. Here's how we can implement it:
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
salary INT CHECK (salary >= 0)
);
Now, if we try to insert data into the employees
table where the salary is less than 0, MySQL will throw an error and not allow the data to be inserted.
Output
When we run the example code above, MySQL will create a new table called employees
with a check constraint that ensures the salary is greater than or equal to 0.
If we try to insert data into the employees
table where the salary is less than 0, MySQL will throw an error and not allow the data to be inserted.
Explanation
In the example above, we created a table called employees
with a check constraint that ensures the salary is greater than or equal to 0. This means that if we try to insert data into the table where the salary is less than 0, MySQL will throw an error and not allow the data to be inserted.
Use
Check constraints are useful for ensuring that the data in a table meets certain conditions. They help maintain data integrity and can prevent invalid data from being inserted into the table.
Important Points
- Check constraints are a type of constraint that checks whether a given condition is satisfied by the columns in a table.
- Check constraints are specified using the
CHECK
keyword in MySQL. - If the condition specified in the check constraint is not satisfied, MySQL will not allow the data to be inserted or updated.
Summary
In this tutorial, we discussed how to create a check constraint in MySQL. We covered the syntax, example, output, explanation, use, and important points of check constraints in MySQL. With this knowledge, you can now use check constraints in your MySQL code to ensure that the data in your table meets certain conditions and to maintain data integrity.