Covering Index and Key Lookup

Columns missing from a nonclustered index are fetched per row by a Key Lookup. Reducing SELECT * to the needed columns lets the index alone answer the query, with no Lookup.

SQL

Situation

A feature downloads the list of "paid orders since June". It actually uses only the order ID and the order time, but the query fetches every column with SELECT *.

Tables

TableColumnDescription
ordersord_idOrder ID (clustered PK)
ordersstatus, ord_dtStatus, order datetime
ordersOtherscust_id, ord_no, amt
IndexColumns
orders_pk (clustered)ord_id
orders_x2status, ord_dt, ord_id

Paid orders since June

**BEFORE · SELECT ***

SELECT o.*
FROM orders o
WHERE o.status = 'PAID'
  AND o.ord_dt >= CAST('2025-06-01' AS datetime2(0))

Run it and check whether it used orders_x2 or read the whole table.

Approach

1. List every column the query uses

If all the columns in SELECT, WHERE, and ORDER BY are in one index, the table does not need to be read.

2. Count the Key Lookup cost

Finding 16,000 rows through orders_x2 means seeking the clustered index 16,000 times to fetch the remaining columns (Key Lookup). The optimizer compares this cost with reading the whole table and picks the cheaper one.

3. Ask whether every column is really needed

SELECT * is what causes the Lookup or the full read.

Explanation

SELECT * → only the needed columns

AFTER · Covering (only the needed columns)

SELECT o.ord_id, o.ord_dt
FROM orders o
WHERE o.status = 'PAID'
  AND o.ord_dt >= CAST('2025-06-01' AS datetime2(0))

Why it got faster

  • In Before, the optimizer judges a Clustered Index Scan of the whole table cheaper than 16,000 Key Lookups. Buffers are about 13,200.
  • In After, ord_id, ord_dt, and status are all in orders_x2, so a single Index Seek finishes the query. Buffers are about 53.

Variation: forcing the index

TRY · Index hint (Key Lookup)

SELECT o.*
FROM orders o WITH (INDEX(orders_x2))
WHERE o.status = 'PAID'
  AND o.ord_dt >= CAST('2025-06-01' AS datetime2(0))
  • After the Index Seek (53), a Clustered Index Seek (Key Lookup) runs 16,479 times, and Buffers are about 47,400. That is more than three times the cost of reading the whole table. The cost is not "using an index is fast" but "how many times it goes back to the table".

Key points

  • Key Lookup: seeking the clustered index again for each row to fetch columns missing from a nonclustered index. With many rows it costs more than a full read.
  • Covering: if every column the query uses is in the index, the Lookup disappears. Columns not used for ordering can be appended as in INCLUDE (amt) (a structural change, so this lab does not do it).
  • Differences by DB: in Oracle, TABLE ACCESS BY INDEX ROWID plays the same role, and in PostgreSQL, heap access does. When covered, the table access disappears or becomes an Index Only Scan, respectively.