Consider a table of values and hashes, like so:
+------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| val | char(9) | NO | | NULL | |
| val_hashed | char(50) | YES | | NULL | |
+------------+----------+------+-----+---------+----------------+
The following query finishes in 0.00 seconds:
SELECT * FROM hashes ORDER BY 1 DESC LIMIT 1;
However, this query takes 3 min 17 seconds:
SELECT val FROM hashes ORDER BY 1 DESC LIMIT 1;
I see that while the query is running the process list shows it as status Sorting result. The situation is completely reproducible. Note that there is another process performing INSERT operations on the table continuously.
Why would the more specific query take longer to run than the * query? I've always believed that * queries should be avoided specifically for performance reasons.
idto find the first row. The second one needs to sort the complete result on the (un indexed)valcolumn. – Jul 27 '14 at 11:20ORDER BY NUMBERsyntax is quite error prone. – usr Jul 27 '14 at 14:52SELECT *combined with a column index inORDER BYis obfuscating which column is being sorted - another reason to avoid*s... – lc. Jul 28 '14 at 04:06*is not explicit. So saying "give me all the columns and sort by the third one" is about as deterministic as saying "go to the supermarket and tell me how many traffic lights you passed" – lc. May 07 '15 at 05:18