How to set the default value of a MySQL field

How to set the default value of a MySQL field

Preface:

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

1. Default value related operations

We can use the DEFAULT keyword to define default values. Default values ​​are usually used in non-empty columns to prevent errors when entering data into the data table.

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

# Format template <field name> <data type> DEFAULT <default value>

# Examplemysql> 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)

From the above experiments, we can see that when the default value is set for the field, when inserting data, if the value of the field is not specified, the default value will be used.

There are other operations about default values, such as modifying default values, adding default values, deleting default values, etc. Let’s look at how this should work.

# Add a new field and set the default value alter table `test_tb` add column `col3` varchar(20) not null DEFAULT 'abc';

# Modify the original default value 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';

# Delete the original default value alter table `test_tb` alter column `col3` drop default;

# Increase default value (similar to modification)
alter table `test_tb` alter column `col3` set default '3aa';

2. Some usage suggestions

In fact, not only non-empty fields can set default values, but ordinary fields can also set default values. However, it is generally recommended to set fields 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 default is the current time, the default is not deleted, the default value of a certain status is 1, and so on. The following table briefly shows some commonly used default value fields.

CREATE TABLE `default_tb` (
  `id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'Auto-increment primary key',
  ...
  `country` varchar(50) not null DEFAULT '中国',
  `col_status` tinyint not null DEFAULT 1 COMMENT '1: What does it represent 2: What does it represent...',
  `col_time` datetime NOT NULL DEFAULT '2020-10-01 00:00:00' COMMENT 'What time',
  `is_deleted` tinyint not null DEFAULT 0 COMMENT '0: Not deleted 1: Deleted',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Creation time',
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'modification time',
  PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

Here we also need to remind you that the default value must match the field type. For example, if a field represents a status value, it may take the value 1, 2, 3... Then it is recommended to use the tinyint type for this field instead of the char or varchar type.

Based on my personal experience, I would like to summarize some suggestions on the use of default values:

Setting default values ​​for non-null fields can prevent insertion errors.

Default values ​​can also be set on nullable fields.

It is best to give notes to some status value fields to indicate what status a certain value represents.

The default value must match the field type.

Summarize:

This article mainly talks about the knowledge related to the default value of MySQL fields. It is relatively simple and easy to understand. I hope you can gain something from it.

The above is the detailed content on how to set the default value of MySQL fields. For more information about the default value of MySQL fields, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • How to assign default values ​​to fields when querying MySQL
  • Add a field to the table in the MySQL command line (field name, whether it is empty, default value)
  • MySQL table field setting default value (graphic tutorial and pay attention to details)
  • MySQL table field time setting default value

<<:  Three ways to implement text color gradient in CSS

>>:  Detailed explanation of the use of Vue image drag and drop zoom component

Recommend

Practical method of upgrading PHP to 5.6 in Linux

1: Check the PHP version after entering the termi...

Detailed explanation of Docker data backup and recovery process

The data backup operation is very easy. Execute t...

Recommended tips for web front-end engineers

Let's first talk about the value of web front...

Detailed explanation of Js class construction and inheritance cases

The definition and inheritance of classes in JS a...

Implementation of installing and uninstalling CUDA and CUDNN in Ubuntu

Table of contents Preface Install the graphics dr...

JS Easy to understand Function and Constructor

Table of contents 1. Overview 1.1 Creating a func...

Detailed steps for developing WeChat mini-programs using Typescript

We don't need to elaborate too much on the ad...

CentOS 7.2 builds nginx web server to deploy uniapp project

Panther started as a rookie, and I am still a roo...

Install and configure MySQL 5.7 under CentOS 7

This article tests the environment: CentOS 7 64-b...

Detailed explanation of how to install MySQL on Alibaba Cloud

As a lightweight open source database, MySQL is w...

Detailed explanation of this pointing problem in JavaScript function

this keyword Which object calls the function, and...

Several ways to shut down Hyper-V service under Windows 10

When using VMware Workstation to open a virtual m...

Vue uses WebSocket to simulate the chat function

The effect shows that two browsers simulate each ...

Explanation of the process of docker packaging node project

As a backend programmer, sometimes I have to tink...

Example of implementing grouping and deduplication in MySQL table join query

Table of contents Business Logic Data table struc...