数据库索引是否反向工作?
给定一个数据库表示例:
ID
Name
DateOfBirth
假设我想创建出生日期索引,我可能会按 DateOfBirth 升序
添加索引。如果我的代码现在查询 DOB 升序,它将运行得又好又快。
但是,数据库是否足够智能,可以反向使用索引,即,如果我查询 orderby DateOfBirth 降序,它是否仍然能够利用该索引,或者我应该专门为降序创建另一个索引?
Given a database table example:
ID
Name
DateOfBirth
Say I wanted to create an index on date of birth, I might add the index on DateOfBirth ascending
. If my code now queries on DOB ascending, it will run nice and fast.
However, are databases intelligent enough to use the index in reverse, i.e, if I queried orderby DateOfBirth descending
would it still be able to utilise that index, or should I create another one specifically for descending ordering?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
索引页形成一个双向链表,如下所示,其中包含指向下一页和上一页的指针。
因此 SQL Server 可以前后遍历索引。扫描方向 显示在执行计划的属性中。
Asc/Desc 变得重要的地方是在复合索引中。
例如,如果索引定义为
ID ASC、Name ASC、DateOfBirth ASC
,则仍需要对查询ORDER BY ID ASC、Name DESC、DateOfBirth ASC
进行排序。请注意,您可能拥有比您意识到的更多的复合索引以及非唯一非聚集索引 将聚集索引键值添加到其键。
The index pages form a doubly linked list as shown below with pointers to both the next and previous page.
Thus SQL Server can traverse the index both backwards and forwards. The Scan direction is shown in the properties of the execution plan.
Where the
Asc
/Desc
becomes important is in composite indexes.If the index was defined as
ID ASC, Name ASC, DateOfBirth ASC
this would still require a sort for the queryORDER BY ID ASC, Name DESC, DateOfBirth ASC
for example.Note that you may have more composite indexes than you realise as well as a non unique non clustered index will have the clustered index key value added to its key.