Imagine I have this SQL query and the table2 is HUGE.
select product_id, count(product_id)
where table2_ptr_id in (select id
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:
Description of the steps you can take to speed up the query.
The optimal indexes for this query, which you can copy and create in your database.
An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
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.
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:
table2.author IS NOT NULL
table1.table2_ptr_id = table2.id