views:

77

answers:

2

i have a query like this

  SELECT TOP 10 
         * 
    FROM NEWS 
   WHERE newsid > AAA 
ORDER BY newsid desc;

this query is very slow for some values of AAA

for example it is fast for 1,000,000 and 1,400,000 but it is slow for 1,355,316

I am confused!!!

A: 

My first thought is that it is doing a lot of string comparison, and that maybe in your case where there are 1,355,316 records, either the string values are long, or the table is fragmented.

Is there an index on the table?

To start reading about query optimization, read this and this.

Gabriel McAdams
what is the difference between 1,300,000 and 1,400,000 or 1,000,000.
ehsan
query executes faster without index!
ehsan
that's why I thought that maybe the table was fragmented. Maybe you could post the execution plans, and tell us - what are all the indexes on the table (including Primary Key).
Gabriel McAdams
If the query executes faster without the index, then maybe your index isn't created as it should be. Show us the execution plans, and tell us what the index is.
Gabriel McAdams
Having an index doesn't ensure it will be used. But there's nothing to support that a SELECT would be faster without an index.
OMG Ponies
after rebuilding index, the query executes fast.but i can not rebuild index every 1 hour! I am collecting news over sites and there are thousands of new records an hour.
ehsan
@ehsan: You can make a SQL Agent job that would.
OMG Ponies
i have a job to rebuild index once a day in midnight. an operation of rebuilding index takes about 5 minutes. so the web site queries will timeout in this 5 minute. it is not good to stop web site!
ehsan
Is NewsId your primary key? Is the index on NewsId Clustered? Why is your NewsId a string?
Gabriel McAdams
And why is your index not set to autorebuild?
Gabriel McAdams
A: 

If in Sql Server 2008 try with FORCESEEK hint. You will get predictable results.

anivas