简体   繁体   中英

Correct order of columns in an index in SQL Server

I have a query that looks like:

select top 1
      a
    , b
    , c
from table
where x = 1
and   y = 2
and   z > getdate()
order by 
      b desc
    , c desc

and an index like:

create index idx_ on table
(
     x
   , y
   , z
   , b
   , c
)
include (a)

My problem is that after the filters I am left with around 6 mil records. And SQL Server won't also sort based on the index, and because of this the times for this query are very big.

The plan looks like:

select (0%) <- TOP N SORT (94%) <= INDEX SEEK (6%)

How can I chose the columns for the index or maybe change the select in such way so that I can benefit from the index.

Also the select has to be able to fit inside an outer apply, which is the main reason for not breaking it up into pieces. The x field being the one on which the outer select links.

As an update to the question, the whole sql looks like:

select 
*
from #tmp_xs xs
outer apply 
  (select top 1
        a
      , b
      , c
  from table
  where x = xs.rel_x
  and   y = 2
  and   z > getdate()
  order by 
        b desc
      , c desc) xs_res

For some reason for the above query sql server will use only the filtering index. If the inner query is placed inside an inline function the result is similar. If I do not put it in an inline function, both indexes work and the query is very fast.

Run your query in SSMS (SQL Server Management Studio) and ask it to produce a Query Plan. It gives hints about indexes that would help and is in fact pretty good at it. Beyond that, @marc_s sounds sensible, but I'd still try it out in SSMS first.

That index that you already have might be used for the selecting process - since it has x, y, z in it that are being queried on as the left-most columns.

It cannot however be used for sorting, since the sort columns b and c are not the left-most columns in that index.

I'd suggest you create an index on (x, y, z) for the selection, and a second, separate index on (b, c) for ordering the results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM