I'm trying to figure out why one of my queries is slow and how I can fix it, but I'm a bit puzzled by the results.
I have an orders table with approximately 80 columns and 775179 rows, and I make the following query:
SELECT * FROM orders WHERE id_state = 2 AND id_mp IS NOT NULL ORDER BY creation_date DESC LIMIT 200
which returns 38 rows in 4.5s
When uninstalling ORDER BY I get a nice improvement:
SELECT * FROM orders WHERE id_state = 2 AND id_mp IS NOT NULL LIMIT 200
38 lines at 0.30s
But when deleting LIMIT , without touching ORDER BY , I get even better result:
SELECT * FROM orders WHERE id_state = 2 AND id_mp IS NOT NULL ORDER BY creation_date DESC
38 lines at 0.10s (??)
Why is my LIMIT so hungry?
GOING ON
I tried a few things before posting my answer, and, noticing that I have an index on creation_date (which is a datetime ), I deleted it and the first query now works at 0.10s. Why is this?
EDIT
Ok, I have indexes on the rest of the columns where I have it.
mysql> explain SELECT * FROM orders WHERE id_state = 2 AND id_mp IS NOT NULL ORDER BY creation_date DESC LIMIT 200; +----+-------------+--------+-------+------------------------+---------------+---------+------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+--------+-------+------------------------+---------------+---------+------+------+-------------+ | 1 | SIMPLE | orders | index | id_state_idx,id_mp_idx | creation_date | 5 | NULL | 1719 | Using where | +----+-------------+--------+-------+------------------------+---------------+---------+------+------+-------------+
1 row per set (0.00 s)
mysql> explain SELECT * FROM orders WHERE id_state = 2 AND id_mp IS NOT NULL ORDER BY creation_date DESC; +----+-------------+--------+-------+------------------------+-----------+---------+------+-------+----------------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+--------+-------+------------------------+-----------+---------+------+-------+----------------------------------------------------+ | 1 | SIMPLE | orders | range | id_state_idx,id_mp_idx | id_mp_idx | 3 | NULL | 87502 | Using index condition; Using where; Using filesort | +----+-------------+--------+-------+------------------------+-----------+---------+------+-------+----------------------------------------------------+
performance sql mysql
Alexandre Jacob
source share