The CHECK constraint in MySQL is used to limit the range of data values in the table, using the syntax: ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK (column_name expression). Advantages include data integrity, performance, and maintainability. Notes are that it only applies to a single column, the expression must return a Boolean value, and the constraint name must be unique.
CHECK constraints in MySQL
In MySQL, CHECK constraints are used to limit the data values in a table. It defines the range of values allowed to be stored in the table by specifying a Boolean expression.
How to use CHECK constraints
To create a CHECK constraint, use the following syntax:
<code class="sql">ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK (column_name expression);</code>
Where:
table_name
is the name of the table to which constraints are to be added. constraint_name
is the unique name of the constraint. column_name
is the name of the column to which the constraint is to be applied. expression
is a Boolean expression that defines the values allowed to be stored in the column. How to use CHECK constraint example
For example, you want to create a table named employees
that only allows positive numbers. ##salary column, you can use the following constraints:
<code class="sql">ALTER TABLE employees ADD CONSTRAINT positive_salary CHECK (salary > 0);</code>
Advantages of CHECK constraints
Using CHECK constraints has the following advantages:Notes on CHECK constraints
The following need to be noted:The above is the detailed content of How to use check constraints in mysql. For more information, please follow other related articles on the PHP Chinese website!