1

While testing my simple mail MySQL db, I found a strange behaviour and would be glad to know why.

My 'mail' table has two primary key :

idx : INT(Auto-Increment)
uid : VARCHAR(50)

with some other dummy columns like createdTime, info, etc.

Then, I've filled my table with 200,000 dummy datas, and tested with a simple search query :

SELECT * FROM mail WHERE uid='RANDOMGENERATEDUID';

It took about 0.235sec to execute this query, and from workbench's tabular explain I found out that this query performs full-table scan and uses no keys.

I was curious that what will happen if I force to use 'idx' column for SELECT query, so, I've tested out another query, which will have the same result :

SELECT * FROM mail
WHERE idx IN (SELECT idx FROM foodwagondb.mail WHERE uid='RANDOMGENERATEDUID');

But what surprised me was that this query executes way more faster, 0.078sec to execute!

What's going on behind my eyes here? I would be happy to know why this happens!

2
  • 1
    One reason could be that in the second sub-query you only select idx which can be retrieved directly from the index alone, without ever accessing the table itself. MySql may decide that when it also needs to select other fields (*), it becomes a little less interesting to use the index, and more interesting to "only" do table access. This decision can depend on several factors, which I am not aware of. But the above could be one element.
    – trincot
    Oct 12, 2018 at 12:54
  • That's interesting... Since second query has much better performance, I'd rather go with this one. Thanks for the reply! Oct 12, 2018 at 13:05

2 Answers 2

0

You shoudl avoid the IN clause and use a INNER JOIN instead

SELECT m1.* FROM mail m1
INNER JOIN foodwagondb.mail m2 ON m2.idx = m1.idx 
WHERE idx m2.uid='RANDOMGENERATEDUID';

the IN clause is equivalent to an OR condition an this implies the related query is repaeat for each values .. the inner join perform just a query and match the resulting values.

Anyway you could improved both the query using a proper composite index for uid to

create index my_index on mail (uid, idx)
1
  • Thanks for the info on IN clause! And yes, composite index accelerates execution time a lot, didn't know about that. Thought just setting up primary key would be sufficient but was not :P Oct 12, 2018 at 13:14
0

In your first query, you search each and every row based on a varchar field (uid). In the second query, mysql pre-filters rows based on an indexed field (idx), then searches that subset for the text string. For smaller tables, you wouldn't see the difference, but for larger ones, it has a performance hit. And @scaisEdge is right, INNER JOIN rules!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.