Home > Database > Mysql Tutorial > What is the use of check constraints in mysql

What is the use of check constraints in mysql

青灯夜游
Release: 2020-09-15 16:29:42
Original
6156 people have browsed it

The role of check constraints in mysql: used to specify the range of possible values ​​for a column. Check constraints can be implemented through CREATE TABLE or ALTER TABLE statements, defined according to the user's actual integrity requirements.

What is the use of check constraints in mysql

In MySQL, CHECK check constraints are provided to specify the range of possible values ​​​​of a certain column. It enforces this by limiting the values ​​entered into the column. domain integrity. However, the current MySQL version only analyzes and processes the CHECK constraint, but it will be directly ignored and no error will be reported.

MySQL check constraints (CHECK) can be implemented through the CREATE TABLE or ALTER TABLE statement, defined according to the user's actual integrity requirements. It can enforce CHECK constraints on columns or tables individually.

Set check constraints when creating the table

Basic syntax:

CHECK(<检查约束>)
Copy after login

Example: Create tb_emp7 data in the test_db database table, the salary field value is required to be greater than 0 and less than 10000

mysql> CREATE TABLE tb_emp7
    -> (
    -> id INT(11) PRIMARY KEY,
    -> name VARCHAR(25),
    -> deptId INT(11),
    -> salary FLOAT,
    -> CHECK(salary>0 AND salary<100),
    -> FOREIGN KEY(deptId) REFERENCES tb_dept1(id)
    -> );
Query OK, 0 rows affected (0.37 sec)
Copy after login

Add check constraints when modifying the table

Basic syntax:

ALTER TABLE tb_emp7 ADD CONSTRAINT <检查约束名> CHECK(<检查约束>)
Copy after login

Example: Modify the tb_dept data table, requiring the id field value to be greater than 0

mysql> ALTER TABLE tb_emp7
    -> ADD CONSTRAINT check_id
    -> CHECK(id>0);
Query OK, 0 rows affected (0.19 sec)
Records: 0  Duplicates: 0  Warnings: 0
Copy after login

Delete the check constraint

Basic syntax:

ALTER TABLE <数据表名> DROP CONSTRAINT <检查约束名>;
Copy after login

The above is the detailed content of What is the use of check constraints in mysql. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
MySQL stops process
From 1970-01-01 08:00:00
0
0
0
Error when installing mysql on linux
From 1970-01-01 08:00:00
0
0
0
phpstudy cannot start mysql?
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template