简体   繁体   中英

Order By clause in RowNumber function slowing down the performance of my query

I have a query which has a paging functionality and for which i'm using ROW_NUMBER() function. The order by clause in my rownumber function is dynamic and gets changed all the time when ever the sp is called. It works fine for few columns but for one column which is of datetime datatype, it takes lot of time. Amazing thing is with when i sort by the same column in descending order, the query runs in a sec but ascending order takes lot of time :(.

I tried creating a non clustered index(as i already i have a clustered index on that table) on that datetime column but it did not help me.

Could you please suggest what i can do to improve the performance.

Thanks,

Deepti

Assuming that this is SQL Server 2005 (I haven't checked 2008), the ROW_NUMBER() function is notorious for causing sensitivity issues in the SQL optimiser. Mr Google will show you numerous examples where a relatively small change such as sort direction causes the optimiser to create a very different execution plan.

Your best bet is to check the cached execution plans to see the differences:

SELECT sc.*
FROM master.dbo.syscacheobjects AS sc
WHERE sc.cacheobjtype = 'Executable Plan'

Alternatively you can change your approach and adapt something nifty like this .

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