Detailed explanation of MySQL field default value setting

Foreword:

In MySQL, we can set default values ​​for table fields. When inserting a new record in the table, if a value is not assigned to a field, the system will automatically insert the default value for this field. Regarding the default value, some knowledge still needs to be understood. In this article, let's learn about the field default value.

1. Default value related operations

We can use the DEFAULT keyword to define the default value. The default value is usually used in non-empty columns, which can prevent errors when entering data in the data table.

When creating a table, we can set a default value for a column, the specific syntax format is as follows:

# 格式模板
<字段名> <数据类型> DEFAULT <默认值>

# 示例
mysql> CREATE TABLE `test_tb` (
    ->   `id` int NOT NULL AUTO_INCREMENT,
    ->   `col1` varchar(50) not null DEFAULT 'a',
    ->   `col2` int not null DEFAULT 1,
    ->   PRIMARY KEY (`id`)
    -> ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0.06 sec)

mysql> desc test_tb;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| col1  | varchar(50) | NO   |     | a       |                |
| col2  | int(11)     | NO   |     | 1       |                |
+-------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql> insert into test_tb (col1) values ('fdg');
Query OK, 1 row affected (0.01 sec)

mysql> insert into test_tb (col2) values (2);
Query OK, 1 row affected (0.03 sec)

mysql> select * from test_tb;
+----+------+------+
| id | col1 | col2 |
+----+------+------+
|  1 | fdg  |    1 |
|  2 | a    |    2 |
+----+------+------+
2 rows in set (0.00 sec)

It can be seen from the above experiment that when the field is set to the default value, when inserting data, if the value of the field is not specified, the default value will be processed.

Regarding the default value, there are other operations, such as modifying the default value, adding the default value, deleting the default value, etc. Let's take a look at how these should be operated.

# 添加新字段 并设置默认值
alter table `test_tb` add column `col3` varchar(20) not null DEFAULT 'abc';

# 修改原有默认值
alter table `test_tb` alter column `col3` set default '3a';
alter table `test_tb` change column `col3` `col3` varchar(20) not null DEFAULT '3b';
alter table `test_tb` MODIFY column `col3` varchar(20) not null DEFAULT '3c';

# 删除原有默认值
alter table `test_tb` alter column `col3` drop default;

# 增加默认值(和修改类似)
alter table `test_tb` alter column `col3` set default '3aa';

2. Some suggestions for use

In fact, not only non-empty fields can be set to default values, but common fields can also be set to default values, but it is generally recommended that fields be set to non-empty.

mysql> alter table `test_tb` add column `col4` varchar(20) DEFAULT '4a';
Query OK, 0 rows affected (0.12 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql>  desc test_tb;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| col1  | varchar(50) | NO   |     | a       |                |
| col2  | int(11)     | NO   |     | 1       |                |
| col3  | varchar(20) | NO   |     | 3aa     |                |
| col4  | varchar(20) | YES  |     | 4a      |                |
+-------+-------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

In project development, some default value fields are still frequently used, such as the current time by default, undeleted by default, and 1 by default for a state value. Simply use the following table to show some commonly used default value fields.

CREATE TABLE `default_tb` (
  `id` int unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键',
  ...
  `country` varchar(50) not null DEFAULT '中国',
  `col_status` tinyint not null DEFAULT 1 COMMENT '1:代表啥 2:代表啥...',
  `col_time` datetime NOT NULL DEFAULT '2020-10-01 00:00:00' COMMENT '什么时间',
  `is_deleted` tinyint not null DEFAULT 0 COMMENT '0:未删除 1:删除',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

I also need to remind here that the default value must match the field type. For example, a field represents the state value, which may take the value 1, 2, 3... Then it is recommended to use the tinyint type instead of char or varchar for this field. Types of.

Based on personal experience, the author summarizes some suggestions on the use of default values:

  • Setting default values ​​for non-empty fields can prevent insert errors.
  • The default value can also be set in the nullable field.
  • Some status value fields are better to give remarks to indicate what status a certain value represents.
  • The default value must match the field type.

to sum up:

This article mainly talks about MySQL field default value related knowledge, which is relatively simple and easy to understand. I hope you will gain something.

Guess you like

Origin blog.51cto.com/10814168/2642201