[Solved] Does SQL execute subqueries fully?

EverSQL Database Performance Knowledge Base

Does SQL execute subqueries fully?

Imagine I have this SQL query and the table2 is HUGE.

select product_id, count(product_id) 
from table1 
where table2_ptr_id in (select id 
                        from table2 
                        where author is not null)

Will SQL first execute the subquery and load all the table2 into memory? like if table1 has 10 rows and table2 has 10 million rows will it be better to join first and then filter? Or DB is smart enough to optimize this query as it is written.

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 `table2` ADD INDEX `table2_idx_id_author` (`id`,`author`);
The optimized query:
SELECT
        table1.product_id,
        count(table1.product_id) 
    FROM
        table1 
    WHERE
        EXISTS (
            SELECT
                1 
            FROM
                table2 
            WHERE
                (
                    table2.author IS NOT NULL
                ) 
                AND (
                    table1.table2_ptr_id = table2.id
                )
        )

Related Articles



* original question posted on StackOverflow here.