[Solved] Nested SQL query takes too long

EverSQL Database Performance Knowledge Base

Nested SQL query takes too long

I'm looking for a way to optimize one SQL query that I have. I'm trying to get how many poems with a certain genre.

Query looks like this:

SELECT
    COUNT(*)  
FROM
    `poems`
WHERE `id` IN (    
                  SELECT `poem_id`
                  FROM `poems_genres`  
                  WHERE `genre_title` = 'derision'
              )
       AND `status` = 'finished';

It takes too long (about 6-10 seconds), because it can't use indexes (because of IN() I think?). Is there a way to rewrite this query in different way to get the same result faster?

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 `poems` ADD INDEX `poems_idx_status` (`status`);
ALTER TABLE `poems_genres` ADD INDEX `poems_genres_idx_genre_title_poem_id` (`genre_title`,`poem_id`);
The optimized query:
SELECT
        COUNT(*) 
    FROM
        `poems` 
    WHERE
        EXISTS (
            SELECT
                1 
            FROM
                `poems_genres` 
            WHERE
                (
                    `poems_genres`.`genre_title` = 'derision'
                ) 
                AND (
                    `poems`.`id` = `poems_genres`.`poem_id`
                )
        ) 
        AND `poems`.`status` = 'finished'

Related Articles



* original question posted on StackOverflow here.