[MySQL] This article takes you to understand database constraints

1. Constraint type

Role:
Database constraints are rules used to restrict data input or data update. Database constraints ensure that only data that conforms to the rules can be inserted into the table to ensure data integrity and consistency.
Common database constraints include:

  1. Primary key constraint: used to uniquely identify each row of data in the table to ensure data uniqueness and integrity.

  2. Foreign key constraints: used to ensure the correctness of the data relationship between tables, and to ensure that the data in the referenced table must exist in the referenced table.

  3. Not Null Constraint: Used to ensure that the values ​​in a column are not null.

  4. Unique Constraint: Used to ensure that the values ​​in a column are not duplicated.

  5. Default constraint: used to set a default value, if the value is not provided when inserting data, the database will use the default value.

  6. Check Constraint: Used to ensure that the values ​​in a column meet a specific condition or expression.

  7. Trigger constraints: Used to automatically perform operations under specific circumstances, such as performing an operation when inserting or deleting data.

2. PRIMARY KEY: primary key constraint

Concept:
A primary key constraint is a database constraint used to restrict the unique identification of each row in a table. A primary key constraint ensures the uniqueness of each row in a table and serves as the basis for relationships between other tables and this table. Each table can only have one primary key constraint , and the value of the primary key constraint must be unique and not empty.
Primary key constraints can be defined when a table is created, or added to an existing table.
Example:
1. When creating a table named "student", you can define a primary key constraint for the "id" column.
primary key constraint
At this time, when we add elements, the value of id must be unique and not empty.
primary key example
>2. When the table has been created, there is no primary key constraint in any column in the table, we can also perform primary key constraint in the following way.
constraint
Note that
this constraint method is not as good as the former, and when the column you want to constrain has null or duplicate elements, the primary key constraint will fail.
fail

The code used above:

mysql> create table student(id int primary key, name varchar(10));
Query OK, 0 rows affected (0.02 sec)

mysql> desc student;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | NO   | PRI | NULL    |       |
| name  | varchar(10) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> insert into values(null,'张三');
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'values(null,'张三')' at line 1
mysql> insert into student values(null,'张三');
ERROR 1048 (23000): Column 'id' cannot be null
mysql> insert into student values('张三');
ERROR 1136 (21S01): Column count doesn't match value count at row 1
mysql> insert into student values(1,'张三');
Query OK, 1 row affected (0.01 sec)

mysql> insert into student values(1,'李四');
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'
mysql> insert into student values(2,'李四');
Query OK, 1 row affected (0.01 sec)

mysql> select * from student;
+----+------+
| id | name |
+----+------+
|  1 | 张三 |
|  2 | 李四 |
+----+------+
2 rows in set (0.00 sec)

3. FOREIGN KEY: foreign key constraints

Concept:
A foreign key constraint is a constraint used to maintain data consistency between tables, which establishes a one-to-many relationship between two tables. Foreign key constraints ensure that data in one table must be related to data in another table, otherwise a constraint error will be triggered.
Foreign key constraints can also be defined at table creation time or added to existing tables.
Example:
Foreign key constraints can also be defined when creating a table or added to an existing table.
The figure below defines a foreign key constraint:
foreign key
foreign key constraints are usually used to establish a one-to-many relationship between two tables. In the figure above, the class_id column in the student table is a foreign key, which is associated with the id in the class table List. This foreign key constraint ensures that the value of the class_id column in the student table can only be selected from the values ​​in the id column in the class table, and if not, an error will be reported.
constraint

The code used above:

mysql> create table class(id int primary key, name varchar(10));
Query OK, 0 rows affected (0.01 sec)

mysql> create table student(id int primary key, name varchar(20), class_id int,
    -> foreign key (class_id) references class(id));
Query OK, 0 rows affected (0.02 sec)

mysql> desc student;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id       | int(11)     | NO   | PRI | NULL    |       |
| name     | varchar(20) | YES  |     | NULL    |       |
| class_id | int(11)     | YES  | MUL | NULL    |       |
+----------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> insert into class values(1, '软件工程'),(2, '计科');
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> insert into student values(20211,'张三',1);
Query OK, 1 row affected (0.01 sec)

mysql> insert into student values(20212,'李四',2);
Query OK, 1 row affected (0.01 sec)

mysql> insert into student values(20213,'王五',3);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`xiaoc`.`student`, CONSTRAINT `student_ibfk_1` FOREIGN KEY (`class_id`) REFERENCES `class` (`id`))

4. NOT NULL: not-null constraint

Concept:
A not-null constraint is a constraint used to ensure that a value in a column is not null. If a not-null constraint is defined for a column, a non-null value must be provided for the column when inserting or updating data, otherwise a not-null constraint error will be triggered.
Example:
When creating a table, you can define a not-null constraint for a column.
The following code defines a table named student, where the id column is defined as a non-null constraint: an error
not-null constraint
will be reported if an empty element is inserted at this time.
Non-empty error

The code used above:

mysql> create table student(id int not null, name varchar(10));
Query OK, 0 rows affected (0.01 sec)

mysql> desc student;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | NO   |     | NULL    |       |
| name  | varchar(10) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.01 sec)

mysql> insert into student values(1,'张三');
Query OK, 1 row affected (0.01 sec)

mysql> insert into student values(null,'李四');
ERROR 1048 (23000): Column 'id' cannot be null
mysql> insert into student values('李四');

5. UNIQUE: unique constraint

Concept:
A unique constraint is a constraint used to ensure that the values ​​in a column are unique. If a unique constraint is defined for a column, the values ​​in the column must be unique and duplicate values ​​are not allowed. Unique constraints can be used to ensure that there are no duplicate values ​​in a column or combination of columns in a table.
Example:
When creating a table, you can define a unique constraint for a column.
The following code defines a table named users, where the email column is defined as a unique constraint:
only
In the above example, the id column in the student table is defined as a unique constraint, so any operation that inserts data into the student table will be You must ensure that the values ​​in the id column are unique.
The only error

The code used above:

mysql> create table student(id int unique,name varchar(20));
Query OK, 0 rows affected (0.02 sec)

mysql> desc student;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | YES  | UNI | NULL    |       |
| name  | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> insert into student values(1,'张三');
Query OK, 1 row affected (0.01 sec)

mysql> insert into student values(2,'李四');
Query OK, 1 row affected (0.01 sec)

mysql> insert into student values(2,'威威');
ERROR 1062 (23000): Duplicate entry '2' for key 'id'

5. DEFAULT: default value constraint

Concept:
The default value constraint means that when a new row is inserted into the table, if no specific value is specified for a column, the column will use a predefined default value. The default value can be any constant or expression, such as a string, number, date, etc. If a column defines a default value constraint, the default value will be used automatically if no specific value is specified for the column when performing an INSERT operation.
Example:
When creating a table, you can specify a default value constraint for a column. For example, the following code creates a table named student, where the name column is defined as a default constraint:
default
when inserting null.
Defaults

The code used above:

mysql> create table student(id int, name varchar(10) default '陌路人');
Query OK, 0 rows affected (0.02 sec)

mysql> desc student;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | YES  |     | NULL    |       |
| name  | varchar(10) | YES  |     | 陌路人  |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> insert into student(id) values(1),(2);
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> insert into student values(3,'张三');
Query OK, 1 row affected (0.01 sec)

mysql> select * from student;
+------+--------+
| id   | name   |
+------+--------+
|    1 | 陌路人 |
|    2 | 陌路人 |
|    3 | 张三   |
+------+--------+
3 rows in set (0.00 sec)

6. Summarize

Database constraint is an important concept in database design. It can effectively guarantee the integrity, consistency, accuracy and security of data, and help developers better manage and maintain data. Therefore, it is very important to master constraints.
The above are the commonly used constraints, see you next time!

Guess you like

Origin blog.csdn.net/weixin_73392477/article/details/131130201