Skip to content
Advertisement

Query slow when use count(*) and inner join

My query is taking around 5 seconds to run. It returns almost 5000 records.

If I remove the Select Count(*) ..., it runs very fast, but I need this data. Is there a way to improve this query?

Thanks

Advertisement

Answer

Indexes recommended by Gordon Linoff are a must-have.

Another thing you could to is move the computation from an inlined query to a joined subquery. This might allow the RDBMS to optimize the query, since it is now explicit that there is no need to repeat the computation for each record (only distinct values of CompanyID actually make a difference):

Another option would be to turn merge the subquery with the outer query (by adding more joins to the outer query), turn on aggregation on the entire outer query, and use a unique column in table Units or Properties to do the count . I am not a big fan of this one, as, usually, the earlier you aggregate the better efficiency you get.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement