Search code examples
sqloptimizationquery-optimizationsql-optimization

SQL (any) Request for insight on a query optimization


I have a particularly slow query due to the vast amount of information being joined together. However I needed to add a where clause in the shape of id in (select id from table).

I want to know if there is any gain from the following, and more pressing, will it even give the desired results.

select a.* from a where a.id in (select id from b where b.id = a.id)

as an alternative to:

select a.* from a where a.id in (select id from b)

Update: MySQL Can't be more specific sorry table a is effectively a join between 7 different tables. use of * is for examples

Edit, b doesn't get selected


Solution

  • Your question was about the difference between these two:

    select a.* from a where a.id in (select id from b where b.id = a.id)
    
    select a.* from a where a.id in (select id from b)
    

    The former is a correlated subquery. It may cause MySQL to execute the subquery for each row of a.

    The latter is a non-correlated subquery. MySQL should be able to execute it once and cache the results for comparison against each row of a.

    I would use the latter.