// troubleshooting guide

Key lookups and covering indexes

An index found the rows, but the query needs columns the index does not have, so the plan fetches every row from the table one at a time. How to see that step on each engine, cover the query with the right index, and when the lookup is fine.

Covers SQL Server PostgreSQL MySQL SQLite Oracle

The symptom

An index holds its key columns and a pointer to the row. When the query asks for any other column, the engine follows the pointer for every row the index returns. SQL Server draws that step as a Key Lookup (或一个 RID Lookup on a heap), Oracle as TABLE ACCESS BY INDEX ROWID. PostgreSQL, MySQL and SQLite do the same work without a separate operator: you recognise it by the difference between an index scan and an index-only or covering scan.

Twenty lookups are nothing. Forty thousand are forty thousand random reads, and well before that point the optimizer gives up on the index and scans the table instead. The examples use a shop schema with 400,000 orders, where customer 4242 has 20 orders and customer 1 has 40,000. Paste your own plan into the query plan viewer to see how many times its lookup ran.

Diagnose it

SQL Server: Key Lookup under a Nested Loops join

With an index on CustomerId only, a query that also returns OrderDate 和 Total has to go back to the clustered index for them:

CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId);
GO
SET STATISTICS IO ON;
SET STATISTICS XML ON;
GO
SELECT OrderId, OrderDate, Total FROM dbo.Orders WHERE CustomerId = 4242;
Table 'Orders'. Scan count 1, logical reads 64, physical reads 0

The plan is a Nested Loops join with an Index Seek on top and a Key Lookup (Clustered) below it that runs once per row. In the plan XML the lookup is a Clustered Index Seek 与 Lookup="1", and its Output List names the columns the index was missing. Now ask for the customer with 40,000 orders:

SELECT OrderId, OrderDate, Total FROM dbo.Orders WHERE CustomerId = 1;
Table 'Orders'. Scan count 1, logical reads 2579, physical reads 0

The index is no longer used at all. 40,000 lookups would cost more than reading the whole table, so the plan is a Clustered Index Scan. A lookup that is cheap for a small customer turns into a full scan for a large one, which is also one of the classic causes of parameter sniffing trouble.

SQL Server: RID Lookup on a heap

A table without a clustered index is a heap, and its indexes point at physical row locations. The lookup is then a RID Lookup:

SELECT * INTO dbo.OrdersHeap FROM dbo.Orders;
CREATE INDEX IX_OrdersHeap_CustomerId ON dbo.OrdersHeap (CustomerId);
GO
SELECT OrderId, OrderDate, Total FROM dbo.OrdersHeap WHERE CustomerId = 4242;

To list the heaps in a database:

SET STATISTICS XML OFF;
SET STATISTICS IO OFF;

SELECT OBJECT_SCHEMA_NAME(i.object_id) AS schema_name, OBJECT_NAME(i.object_id) AS table_name
FROM sys.indexes AS i
WHERE i.type = 0 AND OBJECTPROPERTY(i.object_id, 'IsUserTable') = 1;

Oracle: TABLE ACCESS BY INDEX ROWID

CREATE INDEX orders_customer_idx ON orders (customer_id);

EXPLAIN PLAN FOR
SELECT order_id, order_date, total FROM orders WHERE customer_id = 4242;

SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
| Id  | Operation                           | Name                | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT                    |                     |    20 |   460 |    21   (0)| 00:00:01 |
|   1 |  TABLE ACCESS BY INDEX ROWID BATCHED| ORDERS              |    20 |   460 |    21   (0)| 00:00:01 |
|*  2 |   INDEX RANGE SCAN                  | ORDERS_CUSTOMER_IDX |    20 |       |     3   (0)| 00:00:01 |

Operation 2 finds the rowids in the index, operation 1 fetches each row from the table. BATCHED means Oracle sorts the rowids by block first, so neighbouring rows are fetched together.

PostgreSQL, MySQL and SQLite: index scan versus covering scan

These engines show the table visit in the name of the scan. PostgreSQL prints Index Scan (或一个 Bitmap Heap Scan) when it visits the table and Index Only Scan when it does not:

CREATE INDEX orders_customer_idx ON orders (customer_id);

EXPLAIN (ANALYZE, BUFFERS)
SELECT order_id, order_date, total FROM orders WHERE customer_id = 4242;
Bitmap Heap Scan on orders  (cost=4.59..84.54 rows=21 width=18) (actual time=0.029..0.055 rows=20.00 loops=1)
  Recheck Cond: (customer_id = 4242)
  Heap Blocks: exact=20
  ->  Bitmap Index Scan on orders_customer_idx  (cost=0.00..4.58 rows=21 width=0) (actual time=0.021..0.021 rows=20.00 loops=1)
        Index Cond: (customer_id = 4242)

MySQL prints Using index 在 Extra column when the index covers the query and leaves it out when InnoDB has to read the row from the primary key. In the tree format the two cases are Covering index lookup 和 Index lookup.

CREATE INDEX orders_customer_idx ON orders (customer_id);

EXPLAIN FORMAT=TREE
SELECT order_id, order_date, total FROM orders WHERE customer_id = 4242;

EXPLAIN FORMAT=TREE
SELECT order_id FROM orders WHERE customer_id = 4242;
-> Index lookup on orders using orders_customer_idx (customer_id=4242)  (cost=7 rows=20)
-> Covering index lookup on orders using orders_customer_idx (customer_id=4242)  (cost=3.02 rows=20)

The second query is covered by the same index because every InnoDB secondary index also stores the primary key columns.

SQLite prints USING INDEX 或者 USING COVERING INDEX:

CREATE INDEX orders_customer_idx ON orders (customer_id);

EXPLAIN QUERY PLAN
SELECT order_id, order_date, total FROM orders WHERE customer_id = 4242;
`--SEARCH orders USING INDEX orders_customer_idx (customer_id=?)

Fix it

Add the missing columns to the index

Put the columns the query reads into the index, so the index alone answers the query. SQL Server and PostgreSQL have an INCLUDE list for columns that are only returned, which keeps them out of the key:

CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId)
    INCLUDE (OrderDate, Total)
    WITH (DROP_EXISTING = ON);
GO
SET STATISTICS IO ON;
GO
SELECT OrderId, OrderDate, Total FROM dbo.Orders WHERE CustomerId = 4242;
SELECT OrderId, OrderDate, Total FROM dbo.Orders WHERE CustomerId = 1;
Table 'Orders'. Scan count 1, logical reads 4, physical reads 0
Table 'Orders'. Scan count 1, logical reads 147, physical reads 0

Both queries are now a single Index Seek. The small customer went from 64 page reads to 4, and the large one from a 2,579-page scan to 147.

CREATE INDEX orders_customer_cover_idx ON orders (customer_id) INCLUDE (order_date, total);

EXPLAIN (ANALYZE, BUFFERS)
SELECT order_id, order_date, total FROM orders WHERE customer_id = 4242;
Bitmap Heap Scan on orders  (cost=4.59..84.54 rows=21 width=18) (actual time=0.041..0.065 rows=20.00 loops=1)
  Recheck Cond: (customer_id = 4242)
  Heap Blocks: exact=20
  ->  Bitmap Index Scan on orders_customer_cover_idx  (cost=0.00..4.58 rows=21 width=0) (actual time=0.032..0.032 rows=20.00 loops=1)
        Index Cond: (customer_id = 4242)

The plan has not changed. The query also returns order_id, which is not in the index: a PostgreSQL index does not carry the primary key, so the table is still visited. Add it to the INCLUDE list as well:

DROP INDEX orders_customer_cover_idx;
CREATE INDEX orders_customer_cover_idx ON orders (customer_id) INCLUDE (order_id, order_date, total);

EXPLAIN (ANALYZE, BUFFERS)
SELECT order_id, order_date, total FROM orders WHERE customer_id = 4242;
Index Only Scan using orders_customer_cover_idx on orders  (cost=0.42..4.79 rows=21 width=18) (actual time=0.015..0.016 rows=20.00 loops=1)
  Index Cond: (customer_id = 4242)
  Heap Fetches: 0

A PostgreSQL index-only scan also depends on the visibility map; if Heap Fetches is not zero, see heap fetches in an index-only scan.

MySQL, SQLite and Oracle have no INCLUDE list. Append the columns to the key instead:

CREATE INDEX orders_customer_cover_idx ON orders (customer_id, order_date, total);

EXPLAIN FORMAT=TREE
SELECT order_id, order_date, total FROM orders WHERE customer_id = 4242;
-> Covering index lookup on orders using orders_customer_cover_idx (customer_id=4242)  (cost=3.04 rows=20)
CREATE INDEX orders_customer_cover_idx ON orders (customer_id, order_date, total);

EXPLAIN QUERY PLAN
SELECT order_id, order_date, total FROM orders WHERE customer_id = 4242;
`--SEARCH orders USING COVERING INDEX orders_customer_cover_idx (customer_id=?)
CREATE INDEX orders_customer_cover_idx ON orders (customer_id, order_date, total, order_id);

EXPLAIN PLAN FOR
SELECT order_id, order_date, total FROM orders WHERE customer_id = 4242;

SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
| Id  | Operation        | Name                      | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT |                           |    20 |   460 |     3   (0)| 00:00:01 |
|*  1 |  INDEX RANGE SCAN| ORDERS_CUSTOMER_COVER_IDX |    20 |   460 |     3   (0)| 00:00:01 |

这 covering index page compares the syntax across engines.

Ask for fewer columns

The lookup exists because of the select list. SELECT * can never be covered by a narrow index. If the code only uses three columns, select three columns, and an index that already exists may cover the query as it is.

Give a heap a clustered index

On SQL Server a heap makes every index lookup a RID Lookup. Unless the table is a staging table that is loaded and truncated, give it a clustered index, normally on the primary key:

CREATE UNIQUE CLUSTERED INDEX CX_OrdersHeap ON dbo.OrdersHeap (OrderId);

Do not cover everything

Every included column is stored again in the index and written again on every update of that column. Compare the sizes before you add five columns to an index:

SELECT pg_size_pretty(pg_relation_size('orders')) AS table_size,
       pg_size_pretty(pg_relation_size('orders_customer_idx')) AS narrow_index,
       pg_size_pretty(pg_relation_size('orders_customer_cover_idx')) AS covering_index;
table_size | narrow_index | covering_index
35 MB      | 3024 kB      | 15 MB

An index that includes most of the table's columns is a second copy of the table. Cover the two or three queries that run constantly, and leave the rest with their lookups.

When to leave the lookup alone

Leave it when the index returns few rows: a lookup for 20 rows costs a few dozen page reads. Leave it for queries that run rarely. Fix it when the lookup runs thousands of times per execution, when it is the most expensive operator in the plan, or when the optimizer switches to a full scan for some parameter values because the lookups would be too many.

The checklist

Work through it in order. Each step gives you the evidence for the next one.

  1. Find the lookup: Key Lookup or RID Lookup (SQL Server), TABLE ACCESS BY INDEX ROWID (Oracle), a non-covering index scan elsewhere.
  2. Read how many times it runs: the row count coming out of the index seek.
  3. List the columns the lookup fetches (the Output List in SQL Server).
  4. Check whether the query needs all of those columns; trim the select list first.
  5. Add the remaining columns to the index: INCLUDE on SQL Server and PostgreSQL, key columns elsewhere.
  6. Re-capture the plan and confirm a single seek or a covering scan, with fewer reads.
  7. Compare index size before and after, and do not cover queries that run rarely.

Questions that come up

What is the difference between a Key Lookup and a RID Lookup?

Both fetch the rest of a row after a nonclustered index found it. A Key Lookup goes to the clustered index using the clustering key. A RID Lookup appears when the table is a heap, with no clustered index, and goes to the row's physical location.

Why did SQL Server stop using my index and scan the table?

Because the number of rows it expects makes the lookups more expensive than one pass over the table. Each lookup is a separate read of the clustered index, so past a small share of the table the scan wins. A covering index removes the lookups and with them the tipping point.

Should included columns go in the key or in INCLUDE?

Columns the query filters, joins or sorts on belong in the key. Columns that are only returned belong in INCLUDE on SQL Server and PostgreSQL: they are stored only in the leaf level and do not affect the order of the index. MySQL, SQLite and Oracle have no INCLUDE, so the columns are appended to the key.

Does MySQL have key lookups?

Yes, but the plan does not draw them. InnoDB secondary indexes store the primary key, and a query that needs other columns reads the row from the primary key for each index entry. The plan shows Using index in the Extra column, or Covering index lookup in the tree format, only when that second read is avoided.

Is a covering index always worth it?

No. It makes the index larger and every write to the included columns more expensive. It is worth it for queries that run often and return enough rows for the lookups to show up in the plan's cost.

// fix it where the query lives

Run these queries in SQLly

SQLly is a native SQL workbench for macOS, Windows and Linux. The query plan viewer and formatter these guides link to are built into its editor.