Primary key Ascending vs Descending

我是研究僧i 提交于 2019-11-29 11:16:57

问题


In Sql Server, I have a table with an Identity primary key. Often I want the latest few new records, so I grab the Top n sorted by descending the primary key. Should I define the Primary Key index as Descending, or does it make no difference? i.e. if they are in Ascending order, then can sql just as efficiently work backwards?


回答1:


From a purely querying standpoint, it makes no difference whether your key is descending or ascending if you want to pull N most recent or N oldest records:

The internal algorithms of SQL Server can navigate equally efficiently in both directions on a single-column index, regardless of the sequence in which the keys are stored. For example, specifying DESC on a single-column index does not make queries with an ORDER BY IndexKeyCol DESC clause run faster than if ASC was specified for the index.

http://msdn.microsoft.com/en-us/library/aa933132(SQL.80).aspx

However under just about any normal circumstance, you want your primary key to be ascending and ordinally sequential to prevent fragmentation. SQL Server is optimized for physically appending new records to the end of the database file. If it needs to insert each new record at the top and push everything down, it would probably result in nearly 100% fragmentation.




回答2:


It makes absolutely no difference.

I can't even imagine why it's possible to declare it either way.



来源:https://stackoverflow.com/questions/649307/primary-key-ascending-vs-descending

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!