📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is a covering index in SQL Server, and how do INCLUDE columns differ from key columns? What is a key lookup, when does it become a problem, and how do you decide whether to cover a query?

Covers key lookups and RID lookups, covering indexes, INCLUDE versus key columns, the tipping point where the optimiser switches to a scan, and the write and storage cost of covering.

Intermediate Theory Intermediate covering-index include-columns indexes key-lookup query-performance sql-server

🎯 Key points

  • Key lookup = Nested Loops back into the clustered index for columns the NC index lacks
  • Each lookup costs about 3-4 logical reads (random I/O)
  • Tipping point: past a small percentage of rows the optimiser scans instead
  • Covering index contains every column the query references
  • INCLUDE columns sit only in the leaf: not sorted, not in the 900/1700-byte key limit
  • Key columns for WHERE/JOIN/ORDER BY; INCLUDE for SELECT-only columns
  • Covering widens the index: more writes, storage and memory
  • SELECT * makes covering impossible; project only needed columns

⏱ 30-second answer

A key lookup happens when a non-clustered index finds the rows but lacks some columns the query needs, so SQL Server goes back to the clustered index for each row (a RID lookup on a heap). Each one is 3–4 random logical reads.

A covering index holds every column the query references, so no lookup is needed.

  • Key columns are sorted and searchable: use them for WHERE, JOIN and ORDER BY.
  • INCLUDE columns sit only in the leaf level: not sorted, not counted in the key size limit, cheaper to maintain. Use them for columns that are only selected.

Lookups hurt when they run for thousands of rows; past the tipping point the optimiser scans instead. Trade-off: covering speeds a query but widens the index and every write.

🗣 Full answer (senior)

How I would answer this in an interview

"When a non-clustered index finds the rows for a query but doesn't have all the columns it needs, SQL Server has to go back to the base table for the rest. On a clustered table that's a key lookup: for each row it takes the clustered key from the index leaf and seeks the clustered index, joined with Nested Loops. On a heap it's a RID lookup. Each one is three or four random page reads. For five rows that's nothing. For 20,000 rows it's 80,000 reads, and at some point, usually a small percentage of the table, the optimiser decides a full scan is cheaper and ignores your index. That's the tipping point.

A covering index removes the lookup by containing every column the query references. You can add columns as key columns or as INCLUDE columns. Key columns are part of the sorted B-tree at every level and count towards the 1,700-byte non-clustered key limit; INCLUDE columns are stored only in the leaf pages, aren't sorted and can be types that can't be keys, like nvarchar(max). So I put filter, join and sort columns in the key and the columns that are only selected in INCLUDE.

The mistake I see is covering everything: the missing-index hint suggests six INCLUDE columns, someone adds it, and soon the table has five near-copies of itself and inserts are twice as slow. I cover hot, frequent queries where the lookups are a measurable share of the cost, and I fix the query first if it's selecting columns it doesn't use. Covering trades write cost and memory for read speed, so it should be a decision, not a reflex."


Key vs INCLUDE columns

Key column INCLUDE column
Stored at Every level of the tree Leaf level only
Sorted Yes No
Can be seeked or used for ORDER BY Yes No (filter only as residual)
Size limit 900 B clustered / 1,700 B non-clustered, max 32 columns Not counted; up to 1,023 columns
LOB types (nvarchar(max)) No Yes (but think twice)
Use for WHERE, JOIN, ORDER BY, GROUP BY SELECT-only columns

When a key lookup matters

Situation Action
Few rows (point lookups), lookup is a small share of cost Leave it
Thousands of lookups, high share of the plan cost, hot query Cover with INCLUDE
Query selects columns it never uses Fix the query first
Lookup only for a wide or LOB column Consider not covering; accept the lookup

Production example

A dashboard query read 18,000 recent orders through IX_Orders_OrderDate and did 18,000 key lookups: 57,000 logical reads and 120 ms, run 40 times a minute. Adding INCLUDE (CustomerId, Status, Total) removed the lookup: 210 logical reads and 6 ms. The index grew by 180 MB and insert time rose by under 5%.

🔍 What the interviewer is checking

Checks the candidate can read a key lookup in a plan and make a cost-aware decision about covering it.

Green flags

  • Explains Nested Loops + Key Lookup per row and the tipping point
  • Distinguishes key and INCLUDE columns precisely
  • Knows the clustered key is already in the leaf
  • Weighs write cost and suggests projecting fewer columns

Red flags

  • Covers every query by default
  • Thinks INCLUDE columns can be seeked or sorted
  • Never looks at Output List or executions

📚 Learn in depth

1. Anatomy of a lookup plan

Nested Loops (Inner Join)                          est. rows 18,000
 ├─ Index Seek  IX_Orders_OrderDate                reads ~60 pages
 │    Seek: OrderDate >= @from
 └─ Key Lookup  PK_Orders (Clustered)              executions: 18,000
      Output: CustomerId, Status, Total            ~3 reads each = 54,000

The Key Lookup's Number of Executions equals the outer row count. In the plan properties, its Output List tells you exactly which columns caused it, and any Predicate on it means a filter is being evaluated after the lookup (worse: rows are fetched then discarded).

2. The tipping point

The optimiser costs random lookups much higher than sequential scan reads. For a narrow seek with lookups versus a scan of N pages, the break-even is often a few per cent of the rows, or even under 1% for wide rows. That is why an index that "should" work is ignored for broad date ranges and used for narrow ones. Parameter values change which side of the line you land on, which feeds into parameter sniffing.

3. Where INCLUDE columns live

root / intermediate:  [OrderDate]                    <- key only
leaf:                 [OrderDate | OrderId | CustomerId, Status, Total]
                        key        locator   INCLUDE (unsorted payload)

Because upper levels hold only the key, the tree stays shallow. The leaf is wider, so a range scan reads more pages than the key-only index, but far fewer than the clustered index.

4. The clustered key is always covered

The row locator (clustered key) is in every non-clustered leaf, so a query selecting OrderId from an index on OrderDate is already covered. Do not add the clustered key to INCLUDE; it is redundant.

5. Costs of covering

  • Writes: an update to an included column must update that index too.
  • Storage and memory: wide leaf rows push other data out of the buffer pool.
  • Duplication: covering many different queries drifts towards copies of the table. At that point the clustered index or a columnstore may be the better answer.

6. LOB columns

nvarchar(max) can be included but makes the index large and online rebuild rules stricter; usually accept a lookup for the occasional wide column.

Try it yourself

  1. Query 100 rows and then 100,000 rows by a date range with only a key-only index; watch the plan switch from Seek + Key Lookup to Clustered Index Scan.
  2. Add INCLUDE columns and compare STATISTICS IO for both ranges.
  3. Open the Key Lookup properties and read Output List and Number of Executions.
  4. Compare index sizes with sys.dm_db_partition_stats (used_page_count * 8 / 1024 MB) before and after.
  5. Time a batch of 100,000 inserts with and without the covering index.

💻 Code

Before and after: the same query with a key lookup, then covered with INCLUDE.

-- Before: seek + 18,000 key lookups for CustomerId, Status, Total
CREATE NONCLUSTERED INDEX IX_Orders_OrderDate ON dbo.Orders (OrderDate);

SET STATISTICS IO ON;
SELECT OrderId, CustomerId, Status, Total
FROM dbo.Orders
WHERE OrderDate >= DATEADD(day, -1, SYSUTCDATETIME());
-- Table 'Orders'. Scan count 1, logical reads 57,214

-- After: OrderDate stays the key (it is the range); selected columns move into the leaf
CREATE NONCLUSTERED INDEX IX_Orders_OrderDate
    ON dbo.Orders (OrderDate)
    INCLUDE (CustomerId, Status, Total)
    WITH (DROP_EXISTING = ON, ONLINE = ON);   -- ONLINE needs Enterprise or Azure SQL
-- Table 'Orders'. Scan count 1, logical reads 212   (OrderId is the clustered key: already in the leaf)
-- Find the heaviest key lookups in the plan cache (Output List shows the missing columns)
WITH XMLNAMESPACES (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')
SELECT TOP (20)
    qs.execution_count,
    qs.total_logical_reads / qs.execution_count AS avg_reads,
    SUBSTRING(st.text, 1, 200) AS query_start
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
WHERE qp.query_plan.exist('//IndexScan[@Lookup="1"]') = 1
ORDER BY qs.total_logical_reads DESC;

In .NET, project only the columns you need so a covering index can actually cover the query.

namespace Shop.Reporting;

using Microsoft.EntityFrameworkCore;

public sealed record RecentOrder(int OrderId, int CustomerId, byte Status, decimal Total);

public sealed class RecentOrdersQuery(ShopContext db)
{
    public Task<List<RecentOrder>> RunAsync(DateTime since, CancellationToken ct) =>
        db.Orders
          .AsNoTracking()
          .Where(o => o.OrderDate >= since)
          // Selecting the entity would read every column and force a lookup again.
          .Select(o => new RecentOrder(o.OrderId, o.CustomerId, o.Status, o.Total))
          .ToListAsync(ct);
}

⚠ Common mistakes

  • Mistake: Adding every selected column as a key column. Why it is wrong: wider keys enlarge every tree level and hit the 1,700-byte limit; sorting them gains nothing. Instead: key columns for search and sort, INCLUDE for payload.
  • Mistake: Including the clustered key in INCLUDE. Why it is wrong: it is already in every non-clustered leaf as the row locator. Instead: leave it out.
  • Mistake: Creating every missing-index suggestion with all its INCLUDE columns. Why it is wrong: the suggestions ignore write cost and overlap, so you get near-duplicate copies of the table. Instead: consolidate and cover only hot queries.
  • Mistake: Using SELECT * or loading whole entities. Why it is wrong: no non-clustered index can cover it, so lookups are unavoidable. Instead: project the columns you need.
  • Mistake: Assuming a key lookup is always bad. Why it is wrong: for a handful of rows it is 3 or 4 reads each and covering costs more on writes. Instead: look at executions and share of plan cost.
  • Mistake: Ignoring a Predicate on the Key Lookup operator. Why it is wrong: rows are fetched and then discarded, wasting lookups. Instead: move that column into the index key or INCLUDE so it filters before the lookup.
  • Mistake: Including nvarchar(max) columns by habit. Why it is wrong: LOB data bloats the index and slows maintenance. Instead: accept a lookup for rarely needed wide columns.

🏛 Senior insight: trade-offs

I judge covering by cost share and frequency: a lookup that is 80% of a query run 50 times a second is worth an INCLUDE; one that is 30% of a nightly report is not. Before adding anything I check whether an existing index can be widened instead of adding a new one, because consolidation keeps write cost down.

I also measure the write side. After adding a covering index I compare the write path's duration and log generation (sys.dm_db_index_operational_stats leaf insert and update counts, sys.dm_io_virtual_file_stats for the log) and check that other queries' plans did not change for the worse in Query Store, because a new index can change plan choices elsewhere.

Option When it fits Cost When not to
Accept the lookup Few rows, rare query 3-4 reads per row Thousands of rows on a hot path
INCLUDE columns Hot query, narrow payload Wider leaf, extra writes on those columns Payload is wide or LOB
Widen an existing index An index with the right key exists Slightly larger index It changes the plans of other queries badly
Columnstore Many analytic queries over many columns Different write behaviour Point lookups on OLTP rows

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions including nvarchar(max) columns. Why: Checks they understand why wide types are poor index columns.
    How to answer

    An nvarchar(max) column cannot be a key column of a B-tree index (clustered or non-clustered); it can only sit in INCLUDE or a full-text index, so a lookup on it scans. Values that do not fit in the row (over 8,000 bytes) move to LOB pages, so reading them costs extra I/O, and online index operations were historically restricted. The optimiser also estimates row size from the declared type, assuming a max column is about half-full of a large value, so sorts and hash joins get oversized memory grants that waste memory and reduce concurrency. EF Core maps an unconfigured string to nvarchar(max), so the fix is to give strings realistic lengths with HasMaxLength, a convention, or [MaxLength], and keep max for genuine documents.

  2. When: Candidate mentions projecting only needed columns from EF Core. Why: Checks the EF Core side of writing queries that can use indexes.
    How to answer

    Because the generated SQL applies the function to every row (LOWER([c].[Email]) = @email, DATEPART(year, [o].[PlacedAt]) = 2026), so SQL Server can't seek an index on the raw column. It scans the whole index instead, which costs CPU and reads proportional to the table and gets worse as data grows. Fixes: express dates as a half-open range (WHERE [o].[PlacedAt] >= @start AND [o].[PlacedAt] < @end); rely on the database's case-insensitive collation instead of ToLower(), so no function is needed at all; or index a persisted computed column when you really need the derived value.

↩ Usually asked after

More in Indexes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me