Home Database Mysql Tutorial Slow query problem caused by converting int type to varchar type in MySQL database

Slow query problem caused by converting int type to varchar type in MySQL database

Mar 30, 2017 am 11:02 AM

In the past week, we have processed two slow queries one after another due to the inability to use index when converting int to varchar.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

CREATE TABLE `appstat_day_prototype_201305` (

`day_key` date NOT NULL DEFAULT '1900-01-01',

`appkey` varchar(20) NOT NULL DEFAULT '',

`user_total` bigint(20) NOT NULL DEFAULT '0',

`user_activity` bigint(20) NOT NULL DEFAULT '0',

`times_total` bigint(20) NOT NULL DEFAULT '0',

`times_activity` bigint(20) NOT NULL DEFAULT '0',

`incr_login_daily` bigint(20) NOT NULL DEFAULT '0',

`unbind_total` bigint(20) NOT NULL DEFAULT '0',

`unbind_activitys` bigint(20) NOT NULL DEFAULT '0',

PRIMARY KEY (`appkey`,`day_key`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8

mysql> explain SELECT * from appstat_day_prototype_201305 where appkey = xxxxx and day_key between '2013-05-23' and '2013-05-30';

+----+-------------+------------------------------+------+---------------+------+---------+------+----------+-------------+

| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |

+----+-------------+------------------------------+------+---------------+------+---------+------+----------+-------------+

| 1 | SIMPLE | appstat_day_prototype_201305 | ALL | PRIMARY | NULL | NULL | NULL | 19285787 | Using where |

+----+-------------+------------------------------+------+---------------+------+---------+------+----------+-------------+

1 row in set (0.00 sec)

mysql> explain SELECT * from appstat_day_prototype_201305 where appkey = 'xxxxx' and day_key between '2013-05-23' and '2013-05-30';

+----+-------------+------------------------------+-------+---------------+---------+---------+------+------+-------------+

| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |

+----+-------------+------------------------------+-------+---------------+---------+---------+------+------+-------------+

| 1 | SIMPLE | appstat_day_prototype_201305 | range | PRIMARY | PRIMARY | 65 | NULL | 1 | Using where |

+----+-------------+------------------------------+-------+---------------+---------+---------+------+------+-------------+

1 row in set (0.00 sec)

Copy after login


It can be clearly seen from the above that because the appkey is varchar, and not adding '' to the where condition, it will trigger a full table query. If it is added, the index can be used. The number of rows scanned is very different, and the pressure on the server and the response time are also very different.

Let’s look at another example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

*************************** 1. row ***************************

Table: poll_joined_151

Create Table: CREATE TABLE `poll_joined_151` (

`poll_id` bigint(11) NOT NULL,

`uid` bigint(11) NOT NULL,

`item_id` varchar(60) NOT NULL,

`add_time` int(11) NOT NULL DEFAULT '0',

`anonymous` tinyint(1) NOT NULL DEFAULT '0',

`sub_item` varchar(1200) NOT NULL DEFAULT '',

KEY `idx_poll_id_uid_add_time` (`poll_id`,`uid`,`add_time`),

KEY `idx_anonymous_id_addtime` (`anonymous`,`poll_id`,`add_time`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8

SELECT * FROM poll_joined_151 WHERE poll_id = '2348993' AND anonymous =0 ORDER BY add_time DESC LIMIT 0 , 3

*************************** 1. row ***************************

id: 1

select_type: SIMPLE

table: poll_joined_151

type: ref

possible_keys: idx_poll_id_uid_add_time,idx_anonymous_id_addtime

key: idx_anonymous_id_addtime

key_len: 9

ref: const,const

rows: 30240

Extra: Using where

Copy after login

From the above example, although the type of poll_id is bigint, '' is added to the SQL. But this statement still uses the index. Although there are many rows to be scanned, it is good SQL to use the index.

Why does a small '' have such a big impact? The fundamental reason is that MySQL performs implicit type conversion when comparing text types and numeric types.

The following is the description of the 5.5 official manual:

1

2

3

4

5

6

7

8

9

10

11

If both arguments in a comparison operation are strings, they are compared as strings.

两个参数都是字符串,会按照字符串来比较,不做类型转换。

If both arguments are integers, they are compared as integers.

两个参数都是整数,按照整数来比较,不做类型转换。

Hexadecimal values are treated as binary strings if not compared to a number.

十六进制的值和非数字做比较时,会被当做二进制串。

If one of the arguments is a TIMESTAMP or DATETIME column and the other argument is a constant, the constant is converted to a timestamp before the comparison is performed. This is done to be more ODBC-friendly. Note that this is not done for the arguments to IN()! To be safe, always use complete datetime, date, or time strings when doing comparisons. For example, to achieve best results when using BETWEEN with date or time values, use CAST() to explicitly convert the values to the desired data type.

有一个参数是 TIMESTAMP 或 DATETIME,并且另外一个参数是常量,常量会被转换为 timestamp

If one of the arguments is a decimal value, comparison depends on the other argument. The arguments are compared as decimal values if the other argument is a decimal or integer value, or as floating-point values if the other argument is a floating-point value.

有一个参数是 decimal 类型,如果另外一个参数是 decimal 或者整数,会将整数转换为 decimal 后进行比较,如果另外一个参数是浮点数,则会把 decimal 转换为浮点数进行比较

In all other cases, the arguments are compared as floating-point (real) numbers.所有其他情况下,两个参数都会被转换为浮点数再进行比较

Copy after login

According to the above description, when the type of the value after the where condition is inconsistent with the table structure, MySQL will do implicit type conversion and convert it to a floating point number for comparison.

For the first case:

For example where string = 1;

Need to convert the string in the index into a floating point number, but due to '1',' 1','1a' will all be converted into 1, so MySQL cannot use the index and can only perform a full table scan, resulting in slow queries.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

mysql> SELECT CAST(' 1' AS SIGNED)=1;

+-------------------------+

| CAST(' 1' AS SIGNED)=1 |

+-------------------------+

| 1 |

+-------------------------+

1 row in set (0.00 sec)

mysql> SELECT CAST(' 1a' AS SIGNED)=1;

+--------------------------+

| CAST(' 1a' AS SIGNED)=1 |

+--------------------------+

| 1 |

+--------------------------+

1 row in set, 1 warning (0.00 sec)

mysql> SELECT CAST('1' AS SIGNED)=1;

+-----------------------+

| CAST('1' AS SIGNED)=1 |

+-----------------------+

| 1 |

+-----------------------+

1 row in set (0.00 sec)

Copy after login


At the same time, it should be noted that since they will be converted into floating point numbers for comparison, and floating point numbers are only 53 bits, when the maximum value is exceeded, problems will occur in the comparison.

For the second case:

Since the index is based on int, and the purely numerical string can be converted into a number 100%, it can When an index is used, although certain conversions will be performed and certain resources are consumed, the index is still used in the end and slow queries will not occur.

1

2

3

4

5

6

7

mysql> select CAST( '30' as SIGNED) = 30;

+----------------------------+

| CAST( '30' as SIGNED) = 30 |

+----------------------------+

| 1 |

+----------------------------+

1 row in set (0.00 sec)

Copy after login


The above is the detailed content of Slow query problem caused by converting int type to varchar type in MySQL database. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Monitor Redis Droplet with Redis Exporter Service Monitor Redis Droplet with Redis Exporter Service Apr 10, 2025 pm 01:36 PM

Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

How to view sql database error How to view sql database error Apr 10, 2025 pm 12:09 PM

The methods for viewing SQL database errors are: 1. View error messages directly; 2. Use SHOW ERRORS and SHOW WARNINGS commands; 3. Access the error log; 4. Use error codes to find the cause of the error; 5. Check the database connection and query syntax; 6. Use debugging tools.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

See all articles