The difference between SQL int(1) and int (10)

Preface

Recently I encountered a problem. I had to add a user_idfield to a table, and user_idthe field might be very large, so I submitted a mysql work order alter table xxx ADD user_id int(1). The leader saw my SQL work order and said: int(1)I'm afraid it's not enough. The next step is to give an explanation.

In fact, this is not the first time I have encountered such a problem, and there are many experienced drivers who have worked for more than 5 years. Including that I often see my colleagues using it all the time int(10), I feel that if I use it int(1), the upper limit of the field will be limited. This is definitely not the case in reality.

 

practice

We know that int occupies 4 bytes in mysql, so for unsigned int, the maximum value is 2^32-1 = 4294967295nearly 4 billion. Could it be that if it is used int(1), this maximum value cannot be reached?

CREATE TABLE `user` (
  `id` int(1) unsigned NOT NULL AUTO_INCREMENT,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;

The id field is unsigned int(1), let me insert a maximum value to see.

mysql> INSERT INTO `user` (`id`) VALUES (4294967295);
Query OK, 1 row affected (0.00 sec)

You can see that it is successful, which means that the number after int does not affect the size supported by int itself. There is no difference between int(1), int(2)...int(10).

Zero padding

Generally, the number after int is only effective when used with zerofill. Let’s look at an example first:

CREATE TABLE `user` (
  `id` int(4) unsigned zerofill NOT NULL AUTO_INCREMENT,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;

Note that int(4)a zerofill is added at the end. Let’s insert 4 pieces of data first.

mysql> INSERT INTO `user` (`id`) VALUES (1),(10),(100),(1000);
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

Insert 4 pieces of data: 1, 10, 100, and 1000 respectively, and then let’s query:

mysql> select * from user;
+------+
| id   |
+------+
| 0001 |
| 0010 |
| 0100 |
| 1000 |
+------+
4 rows in set (0.00 sec)

Through the data, we can find that int(4) + zerofill realizes the phenomenon of filling 0 with less than 4 bits, and int(4) alone is useless.

And for 0001, the underlying storage is still 1, but the displayed one will be filled with 0.

Summarize

The number after int cannot represent the length of the field. int(num)Generally, zerofill is added to have an effect. The function of zerofill can generally be used in some number-related numbers, such as student numbers 001 002...999. If mysql does not have the zero-fill function, but you want to format and output equal-length numbers, then You just have to deal with it yourself.

Guess you like

Origin blog.csdn.net/qq_39535439/article/details/134805218