具有 SQL 查詢之索引的用法範例

這些範例顯示如何將索引套用至 SQL 查詢。

範例 1

如果已檢索「嚴重性」或「序列」欄位,則可以在下列 SQL 查詢中使用「嚴重性」欄位上的索引 (提供它是樹狀結構索引) ,因為所有列都必須符合表示式 Severity > 3。 未使用「序列」欄位上的索引,因為使用 OR 運算子來連接兩個述詞。
select Summary from alerts.status where 
   Severity > 3 and (Serial = 102 or ServerName = 'NCOMS');

範例 2

如果在「嚴重性」欄位上建立樹狀結構索引,則可以在下列 SQL 查詢中使用「嚴重性」欄位上的索引。 不過,由於 LastOccurrence > getdate() - 360 述詞與 Summary like 'LinkUp' 述詞之間的 OR 運算子,因此無法使用 LastOccurrence 上的索引。 不過請注意,在查詢期間,表示式 getdate() - 360 被視為常數。
select Summary, Severity, Node from alerts.status where 
   Severity > 1 and (LastOccurrence > getdate() - 360 or Summary like 'LinkUp')

範例 3

請考量下列查詢:
select Summary from alerts.status where Severity > 0;

For a comparison operator like >, >=, <, or <= to be used with an index, a tree index (which is an ordered index) is required. 如果 20,000 中只有 100 列具有 Severity 0 ,則這類索引只會將檢查的列數減少 0.5% ,而且不會提供顯著的效能好處。 因此,必須將實際列資料納入考量,以決定要編製索引的直欄。

範例 4

如果在「節點」直欄上建立雜湊索引,則當執行下列 SQL 查詢時,只會對工具、長條及工具列執行三次雜湊查閱,而不是檢查每一列的「節點」相等及三個值之一。
select Identifier from alerts.status where Node in ('tool', 'bar', 'toobar');

範例 5

如果在「嚴重性」直欄上建立樹狀結構索引,則在處理下列 SELECT 陳述式時,只會搜尋並傳回「嚴重性」值 2 和 3。
select * from alerts.status where Severity > 1 and Severity < 4;
如果 ORDER BY 子句包含多個直欄,則會將索引用於第一個直欄 (如果有的話)。
select Identifier, Serial from alerts.status order by Severity;

範例 6

如果 alerts.status 表格中有 20,000 列,且 ServerSerial 欄位上的索引套用至下列查詢,則只會檢查兩列而非 20,000:
select Summary from alerts.status where ServerSerial in (102,103);

範例 7

Tivoli ® Netcool/OMNIbus 支援透過 SQL 查詢中的次選取子句來使用索引,例如在下列範例中:

select * from alerts.status where Identifier in (select key from alerts.bar);
select * from alerts.status where Serial in (select serial from alerts.broken_events);