Skip to content
Advertisement

SQL Server Query filter with order is slow

I have been struggling with this for a while.

I have a database with three tables (each of which has millions of records) as follows (removed some columns for simplicity):

There exists indexes As follows

To eliminate the possibility that the slowness is because of the selected columns, I only select a fixed value

The following query runs very fast (less than 1 second):

The following query also runs very fast:

And the following as well runs fast:

BUT, the following query runs VERY SLOW (roughly 10 seconds):

I don’t know the reason, and I don’t find any way to apply any more indexes so the query runs faster

Any help is appreciated!

Edit: the following queries also runs fast:

And

The problem appears only with order by and the two filters

Advertisement

Answer

For anyone who is concerned, this is the solution to the problem:

It turned out that with that much rows, what was taking time is to make key lookups and hash matches due to different indexes, so the solution was to add the following index to allow using of a single index on the table for all filter (and order by) values:

But since I may also filter by code in some situations and not only use order by, so I modified the index to be like this:

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