int 4 bytes

http://waynewhitty.ie/blog-post.php?id=19

MySQL - INT(11) vs BIGINT(11) vs TINYINT(11)

This seems to be a common misconception among many developers who interact with MySQL. The assumption is that the 11 inINT(11) determines the maximum size of the integer that the column can store. i.e. That a column set to INT(11) will hold an integer value up to 11 digits in length and that a column set to INT(6) will hold an integer value that is up to 6 digits in length.This misconception exists because of three reasons:

  1. Developers rarely get caught out by it. This is because a regular integer column can store integer values up to 2147483647. That‘s close to 2.15 billion. This means that an integer primary key wont "hit the ceiling" until the table in question holds more than 2 billion rows. In most cases, this never happens.
  2. String data types such as CHAR and VARCHAR do allow you to specify the maximum length. For example: A column set toVARCHAR(30) will only hold 30 characters or less. Anything over that amount will be truncated.
  3. A lot of developers never read the manual.

So, if the 11 in INT(11) isn‘t a determinant for the column‘s maximum size, what is? Simply put: It‘s the data type itself that determines the maximum value. For instance: A regular TINYINT column will always have a max value of 127, an INT column will always have a maximum value of 2147483647 and a BIGINT column will always have a maximum value of 9223372036854775807. The number in brackets has zero affect on the size of the integer being stored. To get a full list of the ranges of integer data types, have a look at the official manual.

What does the number in brackets actually do?

To be honest, the number in brackets is kind of usless unless you‘re using the ZEROFILL attribute. All it does is tell MySQL what width to display the column at when the table‘s data is being viewed via the MySQL console. If you‘re using the ZEROFILL attribute, the number in brackets will tell MySQL how many zeros to pad incoming integers with. For example: If you‘re using ZEROFILL on a column that is set to INT(5) and the number 78 is inserted, MySQL will pad that value with zeros until the number satisfies the number in brackets. i.e. 78 will become 00078 and 127 will become 00127. To sum it up: The number in brackets is used for display purposes.

Side note

The official MySQL manual  also lists the number of bytes that each integer data type requires. A TINYINT will take up 1 byte. A SMALLINT will take up 2 bytes. An INT will take up 4 bytes. A BIGINT will take up 8 bytes. This means that you should choose your integer data types wisely. Last week, I switched a column from INT(1) to TINYINT(1) because it was only being used to store 1s and 0s. The result? An unncessary 6MB was shaved off the total size of the table. After making similar changes to a few more columns, I had managed to get rid of 25MB of uneeded data. Try to keep this in mind the next time you‘re using an INT instead of a TINYINT or a BIGINT instead of an INT.

MySQL 5.7 Reference Manual  /  ...  /  Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT

12.2.1 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT

MySQL supports the SQL standard integer types INTEGER (or INT) and SMALLINT. As an extension to the standard, MySQL also supports the integer types TINYINTMEDIUMINT, and BIGINT. The following table shows the required storage and range for each integer type.

Type Storage Minimum Value Maximum Value
  (Bytes) (Signed/Unsigned) (Signed/Unsigned)
TINYINT 1 -128 127
    0 255
SMALLINT 2 -32768 32767
    0 65535
MEDIUMINT 3 -8388608 8388607
    0 16777215
INT 4 -2147483648 2147483647
    0 4294967295
BIGINT 8 -9223372036854775808 9223372036854775807
    0 18446744073709551615

MySQL 5.7 Reference Manual  /  ...  /  The CHAR and VARCHAR Types

12.4.1 The CHAR and VARCHAR Types

The CHAR and VARCHAR types are similar, but differ in the way they are stored and retrieved. They also differ in maximum length and in whether trailing spaces are retained.

The CHAR and VARCHAR types are declared with a length that indicates the maximum number of characters you want to store. For example, CHAR(30) can hold up to 30 characters.

The length of a CHAR column is fixed to the length that you declare when you create the table. The length can be any value from 0 to 255. When CHAR values are stored, they are right-padded with spaces to the specified length. When CHAR values are retrieved, trailing spaces are removed unless the PAD_CHAR_TO_FULL_LENGTH SQL mode is enabled.

Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0 to 65,535. The effective maximum length of a VARCHAR is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used. See Section C.10.4, “Limits on Table Column Count and Row Size”.

In contrast to CHARVARCHAR values are stored as a 1-byte or 2-byte length prefix plus data. The length prefix indicates the number of bytes in the value. A column uses one length byte if values require no more than 255 bytes, two length bytes if values may require more than 255 bytes.

If strict SQL mode is not enabled and you assign a value to a CHAR or VARCHAR column that exceeds the column‘s maximum length, the value is truncated to fit and a warning is generated. For truncation of nonspace characters, you can cause an error to occur (rather than a warning) and suppress insertion of the value by using strict SQL mode. See Section 6.1.7, “Server SQL Modes”.

For VARCHAR columns, trailing spaces in excess of the column length are truncated prior to insertion and a warning is generated, regardless of the SQL mode in use. For CHAR columns, truncation of excess trailing spaces from inserted values is performed silently regardless of the SQL mode.

VARCHAR values are not padded when they are stored. Trailing spaces are retained when values are stored and retrieved, in conformance with standard SQL.

The following table illustrates the differences between CHAR and VARCHAR by showing the result of storing various string values intoCHAR(4) and VARCHAR(4) columns (assuming that the column uses a single-byte character set such as latin1).

Value CHAR(4) Storage Required VARCHAR(4) Storage Required
‘‘ ‘    ‘ 4 bytes ‘‘ 1 byte
‘ab‘ ‘ab  ‘ 4 bytes ‘ab‘ 3 bytes
‘abcd‘ ‘abcd‘ 4 bytes ‘abcd‘ 5 bytes
‘abcdefgh‘ ‘abcd‘ 4 bytes ‘abcd‘ 5 bytes

The values shown as stored in the last row of the table apply only when not using strict mode; if MySQL is running in strict mode, values that exceed the column length are not stored, and an error results.

If a given value is stored into the CHAR(4) and VARCHAR(4) columns, the values retrieved from the columns are not always the same because trailing spaces are removed from CHAR columns upon retrieval. The following example illustrates this difference:

mysql> CREATE TABLE vc (v VARCHAR(4), c CHAR(4));
Query OK, 0 rows affected (0.01 sec)

mysql> INSERT INTO vc VALUES (‘ab  ‘, ‘ab  ‘);
Query OK, 1 row affected (0.00 sec)

mysql> SELECT CONCAT(‘(‘, v, ‘)‘), CONCAT(‘(‘, c, ‘)‘) FROM vc;
+---------------------+---------------------+
| CONCAT(‘(‘, v, ‘)‘) | CONCAT(‘(‘, c, ‘)‘) |
+---------------------+---------------------+
| (ab  )              | (ab)                |
+---------------------+---------------------+
1 row in set (0.06 sec)

Values in CHAR and VARCHAR columns are sorted and compared according to the character set collation assigned to the column.

All MySQL collations are of type PADSPACE. This means that all CHARVARCHAR, and TEXT values in MySQL are compared without regard to any trailing spaces. “Comparison” in this context does not include the LIKE pattern-matching operator, for which trailing spaces are significant. For example:

mysql> CREATE TABLE names (myname CHAR(10));
Query OK, 0 rows affected (0.03 sec)

mysql> INSERT INTO names VALUES (‘Monty‘);
Query OK, 1 row affected (0.00 sec)

mysql> SELECT myname = ‘Monty‘, myname = ‘Monty  ‘ FROM names;
+------------------+--------------------+
| myname = ‘Monty‘ | myname = ‘Monty  ‘ |
+------------------+--------------------+
|                1 |                  1 |
+------------------+--------------------+
1 row in set (0.00 sec)

mysql> SELECT myname LIKE ‘Monty‘, myname LIKE ‘Monty  ‘ FROM names;
+---------------------+-----------------------+
| myname LIKE ‘Monty‘ | myname LIKE ‘Monty  ‘ |
+---------------------+-----------------------+
|                   1 |                     0 |
+---------------------+-----------------------+
1 row in set (0.00 sec)

This is true for all MySQL versions, and is not affected by the server SQL mode.

Note

For more information about MySQL character sets and collations, see Section 11.1, “Character Set Support”. For additional information about storage requirements, see Section 12.8, “Data Type Storage Requirements”.

For those cases where trailing pad characters are stripped or comparisons ignore them, if a column has an index that requires unique values, inserting into the column values that differ only in number of trailing pad characters will result in a duplicate-key error. For example, if a table contains ‘a‘, an attempt to store ‘a ‘ causes a duplicate-key error.

https://dev.mysql.com/doc/refman/5.5/en/sql-mode.html#sqlmode_no_auto_value_on_zero

The Most Important SQL Modes

The most important sql_mode values are probably these:

  • ANSI

    This mode changes syntax and behavior to conform more closely to standard SQL. It is one of the special combination modeslisted at the end of this section.

  • STRICT_TRANS_TABLES

    If a value could not be inserted as given into a transactional table, abort the statement. For a nontransactional table, abort the statement if the value occurs in a single-row statement or the first row of a multiple-row statement. More details are given later in this section.

  • TRADITIONAL

    Make MySQL behave like a “traditional” SQL database system. A simple description of this mode is “give an error instead of a warning” when inserting an incorrect value into a column. It is one of the special combination modes listed at the end of this section.

    Note

    The INSERT or UPDATE aborts as soon as the error is noticed. This may not be what you want if you are using a nontransactional storage engine, because data changes made prior to the error may not be rolled back, resulting in a “partially done” update.

When this manual refers to “strict mode,” it means a mode with either or both STRICT_TRANS_TABLES or STRICT_ALL_TABLESenabled.

小结:

0-int(4)  int(11) 区别在于补0的位数,但补0需开启ZEROFILL,二者所占的存储空间一致;

 1 mysql> use w0811;
 2 Database changed
 3 mysql> CREATE TABLE w_int (wint int);
 4 Query OK, 0 rows affected (0.01 sec)
 5
 6 mysql> INSERT INTO w_int VALUES (23);
 7 Query OK, 1 row affected (0.01 sec)
 8
 9 mysql> select * from w_int;
10 +------+
11 | wint |
12 +------+
13 |   23 |
14 +------+
15 1 row in set (0.00 sec)
16
17 mysql>

建议商城类数据库,直接用int 而非int(x)来设计表,客户端需要补全0的话,用php或js脚本实现;application中,tinyint满足需求的话,就不用smallint等,以此来节省空间。

发问:

0-沿袭的误区,misconception,是怎么造成的呢?

时间: 2024-07-31 13:33:23

int 4 bytes的相关文章

Golang之bytes.buffer

bytes.buffer是一个缓冲byte类型的缓冲器存放着都是byte Buffer 是 bytes 包中的一个 type Buffer struct{-} A buffer is a variable-sized buffer of bytes with Read and Write methods. The zero value for Buffer is an empty buffer ready to use. (是一个变长的 buffer,具有 Read 和Write 方法. Buf

c# int与byte[]转换

网络上总结的方法汇总: 1: public byte[] intToByte(int i) { byte[] abyte0 = new byte[4]; abyte0[0] = (byte) (0xff & i); abyte0[1] = (byte) ((0xff00 & i) >> 8); abyte0[2] = (byte) ((0xff0000 & i) >> 16); abyte0[3] = (byte) ((0xff000000 & i)

QT下int与QByteArray的转换

int转QByteArray QByteArray intToByte(int i) { QByteArray abyte0; abyte0.resize(4); abyte0[0] = (uchar) (0x000000ff & i); abyte0[1] = (uchar) ((0x0000ff00 & i) >> 8); abyte0[2] = (uchar) ((0x00ff0000 & i) >> 16); abyte0[3] = (uchar)

java中byte数组与int类型的转换(两种方式)

java中byte数组与int类型的转换,在网络编程中这个算法是最基本的算法,我们都知道,在socket传输中,发送.者接收的数据都是 byte数组,但是int类型是4个byte组成的,如何把一个整形int转换成byte数组,同时如何把一个长度为4的byte数组转换为int类型.下面有两种方式. 方法一 /** * int到byte[] * @param i * @return */ public static byte[] intToByteArray(int i) { byte[] resu

Java中int类型和tyte[]之间转换及byte[]合并

JAVA基于位移的 int类型和tyte[]之间转换 [java] view plaincopy /** * 基于位移的int转化成byte[] * @param int number * @return byte[] */ public static byte[] intToByte(int number) { byte[] abyte = new byte[4]; // "&" 与(AND),对两个整型操作数中对应位执行布尔代数,两个位都为1时输出1,否则0. abyte[

python int对象

class int(object) | int(x=0) -> integer | int(x, base=10) -> integer | | Convert a number or string to an integer, or return 0 if no arguments | are given. If x is a number, return x.__int__(). For floating point | numbers, this truncates towards ze

bytes和bytearray总结

The core built-in types for manipulating binary data are bytes and bytearray. They are supported by memoryview which uses the buffer protocol to access the memory of other binary objects without needing to make a copy. bytearray objects are a mutable

python-1:Number数字类型 之二 相关函数 int.from_bytes,int.to_bytes()

函数格式:int.from_bytes(bytes, byteorder, *, signed=False) 简单demo: [python] view plain copy <code class="language-python">s1 = b'\xf1\xff' print(int.from_bytes(s1, byteorder='big', signed=False)) print(int.from_bytes(s1, byteorder='little', si

大数据Java基础(一)int型与byte型数组的转换

为了在接下来的篇章中讲解用java实现文件的归档和解归档,需要先了解一下Java中int型与byte型数组之间的相互转换. 首先,我们先来看看int型转换成byte型数组. 我们知道,Java中,一个int型占用4个字节,一个byte型占用1个字节,所以,对于一个int型,我们需要一个长度为4的byte型数组来对其进行存储. 31位--24位 23位--16位 15位--8位 7位--0位 一个int型的4个字节如上图所示,假设用来存储的字节数组为bytes[],那么,我们可以用bytes[0]