[Solved] Write correlated subquery in a WHERE Clause as join

EverSQL Database Performance Knowledge Base

Write correlated subquery in a WHERE Clause as join

I have a query like below:

select 
  a.id, a.title, a.description
from
  my_table_name as a
where
  a.id in (select id from another_table b where b.id = 1)

My question is, is there any way I can avoid the subquery in where clause and use it in from clause itself without compromising of performance?

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 `another_table` ADD INDEX `another_table_idx_id` (`id`);
The optimized query:
SELECT
        a.id,
        a.title,
        a.description 
    FROM
        my_table_name AS a 
    WHERE
        EXISTS (
            SELECT
                1 
            FROM
                another_table b 
            WHERE
                (
                    b.id = 1
                ) 
                AND (
                    a.id = b.id
                )
        )

Related Articles



* original question posted on StackOverflow here.