views:

96

answers:

3

This query (part of a sproc) will be executed quite a lot:

SELECT TOP (@numRecords)  BlogPost.postId,BlogPost.creationDate,
        BlogPost.header,BlogPost.markedupContentAbstract
     FROM dbo.BlogPost ORDER BY BlogPost.creationDate DESC

Should I put an index on the 'creationDate' field in the BlogPost table? Should I have a view where BlogPost records are ordered and then just SELECT TOP from that?

Details: using SQL Server 2008.

+4  A: 

An index on CreationDate (Make sute it's Descending Order) is the best route.

For clarity:

CREATE NONCLUSTERED INDEX [IX_BlogPost_CreationDate] 
ON BlogPost
( CreationDate DESC )
Nick Craver
What difference does `DESC` make here?
Quassnoi
May also benefit to INCLUDE the returned columns in the index (at expense of write performance)
AdaTheDev
@Quassnoi: He wants the most recent posts listed first, if the default ordering of the index was used you would still have to specify an ORDER BY when querying the data.
Tony
@Tony: an index can be used for sorting in both directions. You need to specify `ORDER BY` in any case.
Quassnoi
The only potential benefit to explicitly specifying the index direction would be to avoid 'backtracking' through pages that have been loaded in memory for the subsequent rows. There may be some minuscule performance benefit in always reading forwards. There will be no benefit in disk access because the physical location of the 'next page' is not guaranteed. It would be MUCH better to consider whether the write overhead of a covering index (see http://stackoverflow.com/questions/2177433/performing-a-select-top-query-with-an-order-by-should-i-use-an-index-or-a-sort/2177483#2177483) is justified.
Craig Young
@Craig: the blog posts are usually read much more often that written.
Quassnoi
A: 

Simply creating a view won't provide any benefit. You could look into indexed views but I don't remember if you can order by on a view and then put an index on it. I would not recommend this approach since your only pulling from a single table.

You could add an index and that should avoid the sort operation that will be done.

JoshBerke
+2  A: 

You cannot create a view with ORDER BY unless you add a TOP into that view.

You can create an index on creationDate and cover all other columns you use in the SELECT list:

CREATE INDEX ix_blogpost_creationdate__other ON BlogPost (creationDate) INCLUDE (postId, header, markedupContentAbstract)
Quassnoi