The difference between int(1) and int(20) in MySQL

We often encounter data type problems. Among them, int is a common integer type, but in actual use, we may encounter data types such as int(1) and int(20). So, what's the difference between them?

In MySQL, int(M) is an integer type, and the total number of bits that can be stored is 4 bytes (32 bits). Among them, M represents the display width, which is the maximum length of the display. If the number of digits is less than M, the number will be filled with spaces; if the number is greater than M, it will be clipped.

The difference between int(1) and int(20):

int(1): Indicates that the display width is 1, used to control the number of digits in display, and does not limit the storage range.
int(20): Indicates that the display width is 20. It also does not limit the storage range and is used for alignment and display effects.

The main difference between int(1) and int(20) is the different display width, which will affect the display effect of data. However, they are the same in the range of stored values, from -2^31 to
2^31-1. In actual use, we should choose the appropriate data type based on actual needs. If you need to precisely control the display width of data, you can use int(M); if you don't need to precisely control the display width of data, you can use int(1) or int directly.

Test 1: Both int(1) and int(20) can store the maximum value of the int type, indicating that it has no impact on the storage size.

–Create table

CREATE TABLE example_table (
    small_int_col INT(1),
    large_int_col INT(20)
);

– Insert data

INSERT INTO example_table (small_int_col, large_int_col) VALUES (123456789, 123456789);

-search result

SELECT * FROM example_table

Insert image description here

Test 2: zerofill attribute

Padding with zeros using theZEROFILL attribute to maintain a fixed number of digits. This is very useful for application scenarios that require fixed digits, such as order numbers, account numbers, etc.

–Create table

CREATE TABLE example_table_zerofill (
    small_int_col INT(1) ZEROFILL,
    large_int_col INT(20) ZEROFILL
);

– Insert data

INSERT INTO example_table_zerofill (small_int_col, large_int_col) VALUES (123456789, 12345), (123456789, 23456);

-search result

SELECT * FROM example_table_zerofill

Insert image description here

Guess you like

Origin blog.csdn.net/LSW1737554365/article/details/134777988