MySQL basic study notes-choose the appropriate data type

Choose the right data type

1 、 CHAR 与 VARCHAR

CHAR is similar to VARCHAR type, both are used to store strings, but they are stored and retrieved in different ways. CHAR is a fixed-length character type, and VARCHAR is a variable-length character type.

The following table shows the results of saving various string values ​​to CHAR(4) and VARCHAR(4):

value CHAR(4) Storage requirements VARCHAR(4) Storage requirements
‘’ ’ ’ 4 bytes ‘’ 1 byte
'from' 'from' 4 bytes 'from' 3 bytes
‘abcd’ ‘abcd’ 4 bytes ‘abcd’ 5 bytes
‘abcdefgh’ ‘abcd’ 4 bytes ‘abcd’ 5 bytes

When searching, trailing spaces are removed from the CHAR column .


2. TEXT and BLOB

When saving relatively large text, TEXT and BLOB are usually chosen. The main difference between the two is that BLOB can be used to store binary data, such as photos; while TEXT can only store character data. Some problems with TEXT and BLOB:

  1. BLOB and TEXT values ​​can cause some performance problems, especially when performing a large number of delete operations

    The delete operation will leave a large "hole" in the data table. Filling in these "holes" later will have an impact on the performance of the insert. In order to improve performance, it is recommended to use the OPTIMIZE TABLE function to defragment such tables regularly.

  2. You can use synthetic indexes to improve the query performance of large text fields

  3. Avoid retrieving large BLOB and TEXT when unnecessary

  4. Separate BLOB or TEXT columns into separate tables


3. Floating point and fixed point

Floating point numbers are generally used to represent values ​​with decimal points. When a field is defined as a floating-point number type, if the precision of the inserted data exceeds the actual precision defined by the column, the inserted value will be rounded to the actual defined precision value, and then inserted. The rounding process will not report an error.

Fixed-point numbers are different from floating-point numbers. Fixed-point numbers are actually stored as strings, so fixed-point numbers can store data more accurately. If the actually inserted numerical precision is greater than the actual defined precision, a warning will be issued, but the actual precision is inserted according to rounding; if it is in the traditional mode, an error will be reported and the insertion cannot be performed.


4. Date type selection

See "Data Types Supported by MySQL".

Guess you like

Origin blog.csdn.net/qq_36879493/article/details/108092379