查询计划中使用索引和约束可为优化器提供选项,这些选项可以大大缩短查询执行时间。
图: 使用索引的查询计划
for each row in the customer table do:
read the row into C
look up C.customer_num in index on orders.customer_num
for each matching row in the orders index do:
read the table row for O
if O.paid_date is null then
look up O.order_num in index on items.order_num
for each matching row in the items index do:
read the row for I
construct output row and return to user
end for
end if
end for
end for
与不使用索引的计划相比,该查询计划明显降低了成本。同理,一个逆相计划也是可行的,该计划是先读取 orders,然后根据索引在 customer 中查找行。
表中行的物理顺序也将影响索引使用的成本。若表的排序方式与索引相关,那么按索引顺序访问多个表行的开销就会下降。例如:如果 orders 表行是根据 customer 号进行物理排序的,那么对某个给定的 customer 的顺序进行多次检索要比表随机排序时的检索快得多。
在某些情况下,使用索引可能会产生附加费用。有关更多信息,请参阅索引查找开销。