[Solved] SQL query tuning (subquery)

EverSQL Database Performance Knowledge Base

SQL query tuning (subquery)

I have the below query which i want to tune as the query takes more time to run. Please help me out.

select  info_id 
from info_table 
where info_id not in (select info_id 
                      from some_table 
                      where info_id is not null) 
AND  rownum <= 1000 ;

The innerquery is returning millions of rows and hence the problem.

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 `info_table` ADD INDEX `info_table_idx_rownum` (`rownum`);
ALTER TABLE `some_table` ADD INDEX `some_table_idx_info_id` (`info_id`);
The optimized query:
SELECT
        info_table.info_id 
    FROM
        info_table 
    WHERE
        NOT EXISTS (
            SELECT
                1 
            FROM
                some_table 
            WHERE
                (
                    some_table.info_id IS NOT NULL
                ) 
                AND (
                    info_table.info_id = some_table.info_id
                )
        ) 
        AND info_table.rownum <= 1000

Related Articles



* original question posted on StackOverflow here.