Debugging SQL query in MySQL

Recently I started writing SQL query for analyzing and debugging the production code. But I was surprised to see that some queries takes longer time to execute to achieve the same output. I did research and found some interesting stuff about how to debug the SQL query. I have a very simple table who’s definition is as following. In test environment, this table was populated with more then 1000K rows.
 
 

 
 
 

+-----------------------+--------------+------+-----+----------------+
| Field                 | Type         | Null | Key | Extra          |
+-----------------------+--------------+------+-----+----------------+
| id                    | bigint(20)   | NO   | PRI | auto_increment |
| dateCreated           | datetime     | NO   |     |                |
| dateModified          | datetime     | NO   |     |                |
| phoneNumber           | varchar(255) | YES  | MUL |                |
| version               | bigint(20)   | NO   |     |                |
| oldPhoneNumber        | varchar(255) | YES  |     |                |
+-----------------------+--------------+------+-----+----------------+

I executed a very simple query to find the tuple which contains 5107357058 as phoneNumber. It took almost 4 seconds to fetch the result.

select * from Device where phoneNumber = 5107357058;
takes 4 sec.

This simple query should have taken few milliseconds. I noticed that phoneNumber datatype is varchar but in query it is provided as number. When I modify the query to match the datatype, it took few milliseconds.

select * from Device where phoneNumber = '5107357058';
takes almost no time.

After googling and reading post on stackoverflow I found EXPLAIN SQL clouse which helps in debugging the query. The EXPLAIN statement provides information about the execution plan for a SELECTstatement. When I used it to get the information about the two queries I got the following results.

mysql> EXPLAIN select * from Device where phoneNumber = 5107357058;
+----+-------------+-----------+------+---------------------------------------+------+---------+------+---------+-------------+
| id | select_type | table     | type | possible_keys                         | key  | key_len | ref  | rows    | Extra       |
+----+-------------+-----------+------+---------------------------------------+------+---------+------+---------+-------------+
|  1 | SIMPLE      | Device    | ALL  | phoneNumber,idx_Device_phoneNumber    | NULL | NULL    | NULL | 6482116 | Using where |
+----+-------------+-----------+------+---------------------------------------+------+---------+------+---------+-------------+
1 row in set (0.00 sec)

mysql> EXPLAIN select * from Device where phoneNumber = '5107357058';
+----+-------------+-----------+------+---------------------------------------+-------------+---------+-------+------+-------------+
| id | select_type | table     | type | possible_keys                         | key         | key_len | ref   | rows | Extra       |
+----+-------------+-----------+------+---------------------------------------+-------------+---------+-------+------+-------------+
|  1 | SIMPLE      |   Device  | ref  | phoneNumber,idx_Device_phoneNumber    | phoneNumber | 258     | const |    2 | Using where |
+----+-------------+-----------+------+---------------------------------------+-------------+---------+-------+------+-------------+
1 row in set (0.00 sec)

The EXPLAINgives you different query attribute. While analysing the query you should take care of the following attribute.

  • possible_keys : shows the indexes apply to the query
  • key : which key use to find the record. NULL values shows that there was no key used for the query and SQL search linearly, eventually takes long time.
  • rows : SQL query with less number of result-rows, is efficient. One should always try to improve the query and avoid using generic query clouse. The query performance is much evident when executed on large number of records.
  • type : is “The join type”. Ref means All rows with matching index values are read from the table; All means the full table scan.

The two outputs of EXPLAIN clearly indicate the subtle differences. The later query uses the string which is right datatype, results phoneNumber as key and checks only two rows. Whereas the former uses integer in the query which is different datatype and hence SQL converts to integer value to string value and compares with each record present in that table. This results NULL as key and 6482116 as row output. You can also see that the later query type value is ref and former query type value is All, which clearly indicates that the former is a bad query.
 

Reference: Debugging SQL query from our JCG partner Rakesh Cusat at the Code4Reference blog.

Related Whitepaper:

Software Architecture

This guide will introduce you to the world of Software Architecture!

This 162 page guide will cover topics within the field of software architecture including: software architecture as a solution balancing the concerns of different stakeholders, quality assurance, methods to describe and evaluate architectures, the influence of architecture on reuse, and the life cycle of a system and its architecture. This guide concludes with a comparison between the professions of software architect and software engineer.

Get it Now!  

2 Responses to "Debugging SQL query in MySQL"

  1. Igor Madjeric says:

    Hi,

    I like the topic of your blog. But i must admit that it is a little but strange that you having such big differences after running those two queries.

    Can you explain how you measure the time of execution of those queries. I would say that you have those results as consequence of query caching.

    I just can not believe that MySQL needs 4s for converting from an INT to VARCHAR.

  2. Akansha says:

    Your Content is very good.

Leave a Reply


4 × = twenty four



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books