Table of Contents
1. MySQL data types
2. The length and range of MYSQL data types
3. Usage Suggestions
Basic principles for selecting data types
char is similar to varchar
Home Database Mysql Tutorial What are the data types of mysql?

What are the data types of mysql?

Sep 27, 2020 pm 05:00 PM
mysql type of data

Mysql data types include: BOOL, TINY INT, INT, BIG INT, FLOAT, DOUBLE, DECIMAL, CHAR, VARCHAR, TINY TEXT, TEXT, Date, DateTime, TimeStamp, Year, etc.

What are the data types of mysql?

1. MySQL data types

Mainly include the following five categories:

Integer types: BIT, BOOL, TINY INT, SMALL INT, MEDIUM INT, INT, BIG INT

Floating point type: FLOAT, DOUBLE, DECIMAL

String type: CHAR, VARCHAR, TINY TEXT, TEXT, MEDIUM TEXT, LONGTEXT , TINY BLOB, BLOB, MEDIUM BLOB, LONG BLOB

Date type: Date, DateTime, TimeStamp, Time, Year

Other data types: BINARY, VARBINARY, ENUM, SET, Geometry, Point , MultiPoint, LineString, MultiLineString, Polygon, GeometryCollection, etc.

1. Integer type

MySQL data type Meaning (signed)
tinyint(m) 1 byte range (-128~127)
smallint(m) 2 bytes range (-32768~32767)
mediumint(m) 3 bytes range ( -8388608~8388607)
int(m) 4 bytes range (-2147483648~2147483647)
bigint(m) 8 bytes range (-9.22*10 to the 18th power)

Value range If unsigned is added, the maximum The value is doubled. For example, the value range of tinyint unsigned is (0~256).

The m in int(m) represents the display width in the SELECT query result set. It does not affect the actual value range or the display width. I don’t know what the use of this m is.

2. Floating point type (float and double)

##MySQL data typeMeaningfloat(m,d)Single precision floating point type 8-bit precision (4 bytes) m total number, d decimal placesdouble(m,d)Double precision floating point type 16-bit precision (8 bytes) m total number, d decimal places
Suppose a field is defined as float(6,3). If a number 123.45678 is inserted, the actual number stored in the database is 123.457, but the total number is subject to the actual number, that is, 6 digits. The maximum integer part is 3 digits. If you insert the number 12.123456, the stored number is 12.1234. If you insert 12.12, the stored number is 12.1200.

3, fixed point number

Floating point Types store approximate values ​​in the database, while fixed-point types store exact values ​​in the database.

decimal(m,d) The parameter m<65 is the total number, d<30 and d

4. String (char, varchar, _text)

##MySQL data typechar(n)varchar(n)tinytexttextmediumtextlongtext

char and varchar:

1.char(n) If the number of characters stored is less than n, spaces will be added after them, and the spaces will be removed when querying. Therefore, there cannot be spaces at the end of strings stored in char type, and varchar is not limited to this.

2.char(n) fixed length, char(4) will occupy 4 bytes no matter how many characters are stored, varchar is 1 byte of the actual number of characters stored (n< =255) or 2 bytes (n>255),

So varchar(4), storing 3 characters will occupy 4 bytes.

3.Char type string retrieval speed is faster than varchar type.
varchar and text:

1.varchar can specify n, text cannot. The internal storage of varchar is the actual number of characters stored, 1 byte (n<=255) or 2 bytes ( n>255), text is the actual number of characters and is 2 bytes

.

2. The text type cannot have a default value.

3.varchar can directly create an index, and text needs to specify the first number of characters to create an index. The query speed of varchar is faster than that of text. When indexes are created, the index of text does not seem to work.

5. Binary data (_Blob)

1. _BLOB and _text are stored in different ways. _TEXT is stored in text mode. English storage is case-sensitive, while _Blob It is stored in binary format, regardless of case.

2._The data stored in BLOB can only be read out as a whole.

3._TEXT can specify the character set, _BLO does not need to specify the character set.

6. Date and time type

Meaning
Fixed length, up to 255 characters
Fixed Length, up to 65535 characters
Variable length, up to 255 characters
Variable length, up to 65535 characters
Variable length, up to 2 to the 24th power - 1 character
Variable length, up to 2 to the 32nd power - 1 character
MySQL data type Meaning
date Date'2008-12-2'
time Time'12:25:36'
datetime Date time '2008-12-2 22:06:44'
timestamp Automatic storage Record modification time

#If you define a field as timestamp, the time data in this field will be automatically refreshed when other fields are modified, so fields of this data type can store this The time when the record was last modified.

Data type attributes

##DEFAULT Default valuePRIMARY KEYPrimary keyAUTO_INCREMENTAuto increment , suitable for integer types UNSIGNEDUnsignedCHARACTER SET nameSpecifies a character set

2. The length and range of MYSQL data types

List of each data type and byte length:

MySQL keywords Meaning
NULL Data columns can contain NULL values
NOT NULL Data columns are not allowed to contain NULL values
##Year1 is displayed in the format of YYYY. For example: 2009Char(M)MVarChar(M)M Variable length string, requires M<=255Binary(M)MChar-like binary storage, characterized by inserting fixed-length shortfalls and padding 0VarBinary(M )MVariable length binary storage similar to VarChar, characterized by fixed length without padding 0Tiny TextMax :255Case insensitiveTextMax:64KCase insensitiveMedium TextMax:16MCase insensitiveLong TextMax:4G Case insensitive##TinyBlobBlobMediumBlobLongBlobEnumSetGeometryPoint##LineString##MultiPointMultiLineString
Data type Byte length Range or usage
Bit 1 Unsigned [0,255], signed [-128,127] , Tianyuan Blog Note: BIT and BOOL Boolean types both occupy 1 byte
TinyInt 1 Integer [0,255]
SmallInt 2 Unsigned [0,65535], signed [-32768,32767]
MediumInt 3 Unsigned[0,2^24-1], signed[-2^23,2^23-1]]
Int 4 Unsigned [0,2^32-1], signed [-2^31,2^31-1]
BigInt 8 Unsigned [0,2^64-1], signed [-2^63 ,2^63 -1]
Float(M,D) 4 Single precision floating point number. Tianyuan Blog reminds that D here is precision. If D<=24, it is the default FLOAT. If D>24, it will be automatically converted to DOUBLE type.
Double(M,D) 8 Double precision floating point.
Decimal(M,D) M 1 or M 2 Unpacked floating point number, usage is similar to FLOAT and DOUBLE, Tianyuan The blog reminds you that if the Decimal data type is used in ASP, the Decimal read directly from the database may need to be converted into a Float or Double type before operation.
Date 3 is displayed in the format of YYYY-MM-DD, for example: 2009-07-19
Date Time 8 is displayed in the format of YYYY-MM-DD HH:MM:SS, for example: 2009-07-19 11:22:30
TimeStamp 4 is displayed in the format of YYYY-MM-DD, for example: 2009-07-19
Time 3 is displayed in the format of HH:MM:SS. For example: 11:22:30
fixed-length string.

Max:255 Case sensitive
Max:64K Case sensitive
Max:16M Case Sensitive
Max:4G Case Sensitive
1 or 2 Up to 65535 different enumeration values ​​
Up to 8 Up to 64 different values
##Polygon
##MultiPolygon
GeometryCollection

3. Usage Suggestions

1. When specifying the data type, the principle of small size is generally adopted. For example, if you can use TINY INT, it is best not to use INT, and if you can use FLOAT type, it is best not to use DOUBLE type, so It will greatly improve the operating efficiency of MYSQL, especially under large data volume testing conditions.

2. There is no need to design the data table too complicated. The distinction between functional modules may be more convenient for later maintenance. Be careful when presenting a hodgepodge of data tables.

3. The classification of data tables and fields Naming is also a skill

4. Before designing the data table structure, please imagine it is your room. Maybe the result will be more reasonable and efficient

5. The final design result of the database must be It is a trade-off between efficiency and scalability. It is inappropriate to favor either side.

Basic principles for selecting data types

Prerequisite: Use a suitable storage engine.

Selection principle: Determine how to choose the appropriate data type based on the selected storage engine.

The following selection methods are classified by storage engine:

  • MyISAM data storage engine and data columns: MyISAM data table, it is best to use fixed-length (CHAR) data columns instead of variable Data column of length (VARCHAR).
  • MEMORY storage engine and data columns: MEMORY data tables currently use fixed-length data row storage, so it does not matter whether you use CHAR or VARCHAR columns. Both are handled as CHAR types.
  • InnoDB storage engine and data columns: It is recommended to use VARCHAR type.

For InnoDB data tables, the internal row storage format does not distinguish between fixed-length and variable-length columns (all data rows use head pointers pointing to data column values), so in essence , using fixed-length CHAR columns is not necessarily simpler than using variable-length VARCHAR columns. Therefore, the main performance factor is the total storage used by the data rows. Since CHAR takes up more space on average than VARCHAR, it is better to use VARCHAR to minimize the total storage and disk I/O of data rows that need to be processed.

Let’s talk about fixed-length data columns and variable-length data columns.

char is similar to varchar

The CHAR and VARCHAR types are similar, but they are saved and retrieved differently. They also differ in terms of their maximum length and whether trailing spaces are preserved. No case conversion is performed during storage or retrieval.

The following table shows the results of saving various string values ​​into CHAR(4) and VARCHAR(4) columns, illustrating the difference between CHAR and VARCHAR:

Value CHAR(4) Storage Requirements VARCHAR(4) Storage Requirements
'' ' ' 4 bytes '' 1 byte
'ab' 'ab ' 4 bytes 'ab ' 3 bytes
'abcd' 'abcd' 4 bytes 'abcd' 5 characters Section
'abcdefgh' 'abcd' 4 bytes 'abcd' 5 bytes

Please note that the value in the last row in the above table only applies when strict mode is not used ; if MySQL is running in strict mode, the value that exceeds the column length will not be saved , and an error will occur.

The values ​​retrieved from CHAR(4) and VARCHAR(4) columns are not always the same because trailing spaces are removed from the CHAR column when retrieving. The following examples illustrate this difference:

mysql> CREATE TABLE vc (v VARCHAR(4), c CHAR(4));
Query OK, 0 rows affected (0.02 sec)
 
mysql> INSERT INTO vc VALUES (&#39;ab  &#39;, &#39;ab  &#39;);
Query OK, 1 row affected (0.00 sec)
 
mysql> SELECT CONCAT(v, &#39;+&#39;), CONCAT(c, &#39;+&#39;) FROM vc;
+----------------+----------------+
| CONCAT(v, &#39;+&#39;) | CONCAT(c, &#39;+&#39;) |
+----------------+----------------+
| ab  +          | ab+            |
+----------------+----------------+
1 row in set (0.00 sec)
Copy after login

text and blob

When using text and blob field types, please pay attention to the following points in order to better utilize the performance of the database.

①BLOB and TEXT values ​​will also cause some problems of their own, especially when a large number of delete or update operations are performed. Deleting this kind of value will leave a large "hole" in the data table. Records that fill these "holes" in the future may have different lengths. In order to improve performance, it is recommended to regularly use the OPTIMIZE TABLE function to defragment such tables.


②Use synthetic (synthetic) index. Synthetic index columns are useful sometimes. One way is to create a hash value based on the contents of other columns and store this value in a separate data column. You can then find the row of data by retrieving the hash value. However, we should note that this technique can only be used for exact match queries (hash values ​​are not useful for range search operators like < or >=). We can use the MD5() function to generate the hash value, we can use SHA1() or CRC32(), or we can use our own application logic to calculate the hash value. Remember that numeric hash values ​​can be stored very efficiently. Likewise, if a hashing algorithm produces strings with trailing spaces, do not store them in CHAR or VARCHAR columns; they will be affected by trailing space removal.

Synthetic hash indexes are particularly useful for those BLOB or TEXT data columns. A search using a hashed identifier value is much faster than searching the BLOB column itself.

③Avoid retrieving large BLOB or TEXT values ​​when unnecessary. For example, a SELECT * query is not a good idea unless you can be sure that the WHERE clause as a constraint will only find the required rows of data. Otherwise, you could transmit a large number of values ​​over the network without any purpose. This is also an example where it helps us to have BLOB or TEXT identifier information stored in a synthetic index column. You can search the index column to determine which data rows are needed, and then retrieve the BLOB or TEXT value from the qualifying data rows.

④ Separate BLOB or TEXT columns into separate tables. In some environments, it may make sense to move these data columns to a second data table if it allows you to convert the data columns in the original data table to a fixed-length row format. This reduces fragmentation in the main table and gives you the performance benefits of fixed-length data rows. It also allows you to run SELECT * queries on the main data table without transmitting large amounts of BLOB or TEXT values ​​over the network.

Floating point numbers and fixed point numbers

In order to attract everyone's attention, let everyone see an example before introducing floating point numbers and fixed point numbers:

mysql> CREATE TABLE test (c1 float(10,2),c2 decimal(10,2));
Query OK, 0 rows affected (0.29 sec)
mysql> insert into test values(131072.32,131072.32);
Query OK, 1 row affected (0.07 sec)
mysql> select * from test;
+-----------+-----------+
| c1        | c2        |
+-----------+-----------+
| 131072.31 | 131072.32 |
+-----------+-----------+
1 row in set (0.00 sec)
Copy after login

From the above example We see that the value of column c1 has changed from 131072.32 to 131072.31. This is caused by the inaccuracy of floating point numbers.

In mysql, float and double (or real) are floating-point numbers, and decimal (or numberic) is a fixed-point number.

The advantage of floating-point numbers over fixed-point numbers is that when the length is certain, floating-point numbers can represent a larger data range; its disadvantage is that it can cause accuracy problems. In the future applications of floating-point numbers and fixed-point numbers, everyone should remember the following points:


    Floating point numbers have error problems;
  1. is sensitive to precision in currencies, etc. The data should be represented or stored with fixed-point numbers;
  2. In programming, if floating-point numbers are used, special attention should be paid to error issues and try to avoid floating-point comparisons;
  3. Be careful with floating-point numbers Handling of some special values.

The above is the detailed content of What are the data types of mysql?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The relationship between mysql user and database The relationship between mysql user and database Apr 08, 2025 pm 07:15 PM

In MySQL database, the relationship between the user and the database is defined by permissions and tables. The user has a username and password to access the database. Permissions are granted through the GRANT command, while the table is created by the CREATE TABLE command. To establish a relationship between a user and a database, you need to create a database, create a user, and then grant permissions.

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

RDS MySQL integration with Redshift zero ETL RDS MySQL integration with Redshift zero ETL Apr 08, 2025 pm 07:06 PM

Data Integration Simplification: AmazonRDSMySQL and Redshift's zero ETL integration Efficient data integration is at the heart of a data-driven organization. Traditional ETL (extract, convert, load) processes are complex and time-consuming, especially when integrating databases (such as AmazonRDSMySQL) with data warehouses (such as Redshift). However, AWS provides zero ETL integration solutions that have completely changed this situation, providing a simplified, near-real-time solution for data migration from RDSMySQL to Redshift. This article will dive into RDSMySQL zero ETL integration with Redshift, explaining how it works and the advantages it brings to data engineers and developers.

How to fill in mysql username and password How to fill in mysql username and password Apr 08, 2025 pm 07:09 PM

To fill in the MySQL username and password: 1. Determine the username and password; 2. Connect to the database; 3. Use the username and password to execute queries and commands.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Apr 08, 2025 pm 07:12 PM

1. Use the correct index to speed up data retrieval by reducing the amount of data scanned select*frommployeeswherelast_name='smith'; if you look up a column of a table multiple times, create an index for that column. If you or your app needs data from multiple columns according to the criteria, create a composite index 2. Avoid select * only those required columns, if you select all unwanted columns, this will only consume more server memory and cause the server to slow down at high load or frequency times For example, your table contains columns such as created_at and updated_at and timestamps, and then avoid selecting * because they do not require inefficient query se

How to copy and paste mysql How to copy and paste mysql Apr 08, 2025 pm 07:18 PM

Copy and paste in MySQL includes the following steps: select the data, copy with Ctrl C (Windows) or Cmd C (Mac); right-click at the target location, select Paste or use Ctrl V (Windows) or Cmd V (Mac); the copied data is inserted into the target location, or replace existing data (depending on whether the data already exists at the target location).

Understand ACID properties: The pillars of a reliable database Understand ACID properties: The pillars of a reliable database Apr 08, 2025 pm 06:33 PM

Detailed explanation of database ACID attributes ACID attributes are a set of rules to ensure the reliability and consistency of database transactions. They define how database systems handle transactions, and ensure data integrity and accuracy even in case of system crashes, power interruptions, or multiple users concurrent access. ACID Attribute Overview Atomicity: A transaction is regarded as an indivisible unit. Any part fails, the entire transaction is rolled back, and the database does not retain any changes. For example, if a bank transfer is deducted from one account but not increased to another, the entire operation is revoked. begintransaction; updateaccountssetbalance=balance-100wh

See all articles