索引 查詢型別和索引

2021-09-06 08:13:40 字數 2462 閱讀 9250

當您考慮是否要對列建立索引時, 請估計在查詢中使用列的方式, 下表介紹了索引對其有用的查詢型別.

表中的示例基於 adventureworks2008r2 示例資料庫, 在 sql server management studio 中執行這些示例時. 您可以通過顯示實際的執行計畫來檢視查詢優化器選擇的索引. 有關詳細資訊, 請參閱 如何顯示實際執行計畫.

分類

描述

考慮的索引

與特定值完全匹配

搜尋與特定值完全匹配的項. 其中, 查詢使用 where 子句指定列項. 例如:

select businessentityid, jobtitle

from humanresources.employee

where businessentityid = 228;

businessentityid 列的非聚集或聚集索引 

與 in (x,y,z) 列表中的某個值完全匹配

搜尋與指定值列表中的某個值完全匹配的項. 例如:

select businessentityid, jobtitle

from humanresources.employee

where businessentityid in (288, 30, 15);

businessentityid 列的非聚集或聚集索引 

值範圍搜尋某個值範圍, 其中, 查詢指定的任何項的值在兩個值之間. 例如:

select productmodelid, name

from production.productmodel

where productmodelid between 1 and 5;

where productmodelid >= 1 and productmodelid < = 5;

productmodelid 列的聚集索引或非聚集索引 

表之間的聯接

基於聯接謂詞, 在乙個表中搜尋與另乙個表中的某個行匹配的行. 例如:

select a.productassemblyid, b.name, a.perassemblyqty

from production.billofmaterials as a

join production.product as b

on a.productassemblyid = b.productid

where b.productid = 900;

productid 和 productassemblyid 列的聚集索引或非聚集索引 

like 比較

搜尋以特定字串(如 abc%)開頭的匹配行. 例如:

select countryregioncode, name

from person.countryregion

where name like n'd%'

name 列的非聚集或聚集索引 

排序或聚合

需要隱式或顯式排序順序或聚合 (group by). 例如:

select a.workorderid, b.productid, a.orderqty, a.duedate

from production.workorder as a

join production.workorderrouting as b

on a.workorderid = b.workorderid

order by a.workorderid;

排序列或聚合列的非聚集索引或聚集索引 

對於排序列,考慮為列指定 asc 或 desc 順序.

primary key 或 unique 約束

搜尋與插入和更新操作中的新索引鍵值重複的值, 以強制 primary key 和 unique 約束. 例如:

insert into production.unitmeasure (unitmeasurecode, name, modifieddate)

values ('oz1', 'ouncestest', getdate());

約束中定義的列的聚集索引或非聚集索引 

列在選擇列表中,但不在謂詞中.

包含選擇列表中未用於搜尋和查詢的一列或多列.例如:

select title, revision, filename

from production.document

where title like n'%maintenance%' and revision >= 0 ;

在 include 子句中指定了 filename 的非聚集索引.

primary key/foreign key 關係中的 update 或 delete操作

在列參與 primary key/foreign key 關係(無論帶不帶 cascade 選項)的更新或刪除操作中搜尋行.

外來鍵列的非聚集索引或聚集索引.

索引查詢和索引掃瞄

索引的訪問方式主要是 索引查詢 索引掃瞄。在執行計畫中為 index seek,適用於查詢少量資料。對應隨機io,能快速的定位一條資料。在執行計畫中為 index scan,適合掃瞄整個索引的資料。類似於全表掃瞄 只掃瞄索引 對應順序io,io效率本身比較高。索引查詢 和 索引掃瞄,單從io效率上來...

索引型別和索引使用原則

使用索引可快速訪問資料庫表中的特定資訊。索引是對資料庫表中一列或多列的值進行排序的一種結構,與必須搜尋表中的所有行相比,索引會幫助您更快地獲得該資訊。索引提供指向儲存在表的指定列中的資料值的指標,然後根據您指定的排序順序對這些指標排序。資料庫使用索引的方式與您使用書籍中的索引的方式很相似 它搜尋索引...

Oracle索引 索引型別

oracle 提供了多種不同型別的索引以供使用。簡單地說,oracle 中包括如下索引 b 樹索引 這些是我所說的 傳統 索引。到目前為止,這是 oracle 和大多數其他資料庫中最常用的索引。b 樹的構造類似於二叉樹,能根據鍵提供一行或乙個行集的快速訪問,通常只需很少的讀操作就能找到正確的行。不過...