I have this query but it is taking foreever to run. Any suggestions on if it can be changed to run faster?
BTW tablaA has nearly 4 million records and tableB 40,000. I am thinking theres is nothing I can do but figured couldn;t hurt to ask.
This is a simple example that resembles it:
I think indexing this could be a bear. You've got two different filter criteria, one of them a rather wide IN clause (which results in OR statements, which frequently cause scans) and the other a BETWEEN on a text field, again, possibly problematic. Then, on top of it, we get an aggregation against another column with a DISTINCT. Yikes.
First thing I'd do is pivot the IN clause to a temp table and then use a JOIN. You're more likely to get a good execution plan that way. After that... I'd need to see the execution plan to understand how SQL Server is dealing with all the details. Look up Jeff Moden and Tally Table to find great articles on how to do the pivot.
answered Oct 19 '11 at 02:48 PM
Grant Fritchey ♦♦
You can also try this ?
You do not need to count ID field because as per your query it will be always 1.
Agreeing with what all the others have said, I'd like to be a little more specific on the indexing. I'm guessing tablea.ID is the primary key, so that should already be indexed, probably clustered index.
If not, create an index on that column. Apart from that, you should have indexes on colA, colB and colC in both tables. For this specific query, you'd probably do fine with one index containing all three columns, but if you want that or not should also be a consideration with the other queries running against the tables.
tablea.ProdID should definitely be indexed.
To find out which indexes you have, you could either expand Tables->tablea->Indexes in Management Studio, or run a query to find out:
answered Oct 19 '11 at 11:14 PM
I would suggest trying a temp table, as @sqlchamp has shown but I would index it and join on it, not use a nested select
CREATE TABLE #Prod ( ProdID INT )
You will also need to look at the execution plan, consider data types and indexing. Your
answered Oct 20 '11 at 01:03 AM