[Solved] \'IN\' clause in mysql making the execution slower, is there any other choices?
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

\'IN\' clause in mysql making the execution slower, is there any other choices?

Database type:

i have a table named 'language' as shown below

personid |     lang
-------------------
1       |    english
1       |    french
1       |    italian
2       |    italian
3       |    french
3       |    italian
4       |    japanese

I wish to select all personid's with any of the language that personid 1 know. (That is, any personid which have values english, french or italaian)

I have used the following query and got the solution. But it seems little bit slower. (I think it's due to 'IN' clause). Is there any other query option for faster execution.

SELECT distinct personid FROM language WHERE personid!=1 AND lang IN (SELECT lang FROM language WHERE personid=1)

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
  2. Replace In Subquery With Correlated Exists (modified query below): In many cases, an EXISTS subquery with a correlated condition will perform better than a non correlated IN subquery.
Optimal indexes for this query:
ALTER TABLE `language` ADD INDEX `language_idx_personid` (`personid`);
ALTER TABLE `language` ADD INDEX `language_idx_lang_personid` (`lang`,`personid`);
The optimized query:
SELECT
        DISTINCT language.personid 
    FROM
        language 
    WHERE
        language.personid != 1 
        AND EXISTS (
            SELECT
                1 
            FROM
                language AS language1 
            WHERE
                (
                    language1.personid = 1
                ) 
                AND (
                    language.lang = language1.lang
                )
        )

Related Articles



* original question posted on StackOverflow here.