Types in MySQL: BigInt(20) vs Int(20)

前端 未结 6 1510
野性不改
野性不改 2020-11-22 16:15

I was wondering what the difference between BigInt, MediumInt, and Int are... it would seem obvious that they would allow for larger n

6条回答
  •  悲&欢浪女
    2020-11-22 16:49

    As far as I know, there is only one small difference is when you are trying to insert value which is out of range.

    In examples I'll use 401421228216, which is 101110101110110100100011101100010111000 (length 39 characters)

    • If you have INT(20) for system this means allocate in memory minimum 20 bits. But if you'll insert value that bigger than 2^20, it will be stored successfully, only if it's less then INT(32) -> 2147483647 (or 2 * INT(32) -> 4294967295 for UNSIGNED)

    Example:

    mysql> describe `test`;
    +-------+------------------+------+-----+---------+-------+
    | Field | Type             | Null | Key | Default | Extra |
    +-------+------------------+------+-----+---------+-------+
    | id    | int(20) unsigned | YES  |     | NULL    |       |
    +-------+------------------+------+-----+---------+-------+
    1 row in set (0,00 sec)
    
    mysql> INSERT INTO `test` (`id`) VALUES (401421228216);
    ERROR 1264 (22003): Out of range value for column 'id' at row 1
    
    mysql> SET sql_mode = '';
    Query OK, 0 rows affected, 1 warning (0,00 sec)
    
    mysql> INSERT INTO `test` (`id`) VALUES (401421228216);
    Query OK, 1 row affected, 1 warning (0,06 sec)
    
    mysql> SELECT * FROM `test`;
    +------------+
    | id         |
    +------------+
    | 4294967295 |
    +------------+
    1 row in set (0,00 sec)
    
    • If you have BIGINT(20) for system this means allocate in memory minimum 20 bits. But if you'll insert value that bigger than 2^20, it will be stored successfully, if it's less then BIGINT(64) -> 9223372036854775807 (or 2 * BIGINT(64) -> 18446744073709551615 for UNSIGNED)

    Example:

    mysql> describe `test`;
    +-------+---------------------+------+-----+---------+-------+
    | Field | Type                | Null | Key | Default | Extra |
    +-------+---------------------+------+-----+---------+-------+
    | id    | bigint(20) unsigned | YES  |     | NULL    |       |
    +-------+---------------------+------+-----+---------+-------+
    1 row in set (0,00 sec)
    
    mysql> INSERT INTO `test` (`id`) VALUES (401421228216);
    Query OK, 1 row affected (0,04 sec)
    
    mysql> SELECT * FROM `test`;
    +--------------+
    | id           |
    +--------------+
    | 401421228216 |
    +--------------+
    1 row in set (0,00 sec)
    

提交回复
热议问题