Launch price: every exam for $29.99 a year, for the first 300 buyers. See the price

CertStreak
Menu

Identify and implement index changes for queries

A worked example

Single answer

You manage an Azure SQL Database. The Sales.Orders table has a clustered index on OrderID. The nonclustered index IX_Orders_CustomerID already exists and has CustomerID as its only key column.

A frequently run query is:

SELECT CustomerID, OrderDate, TotalDue
FROM Sales.Orders
WHERE CustomerID = @CustomerID;

The actual execution plan shows an Index Seek on IX_Orders_CustomerID followed by a Key Lookup that retrieves OrderDate and TotalDue.

You must remove the Key Lookup by changing IX_Orders_CustomerID in a single statement, without running DROP INDEX. Which statement should you run?

Choose one answer
Why

The Key Lookup retrieves OrderDate and TotalDue because those columns are missing from the nonclustered index. Columns that are only returned by the query should be added as included columns, which makes the index cover the query. Because IX_Orders_CustomerID already exists, recreating it with DROP_EXISTING = ON changes its definition in one statement without a separate DROP INDEX.

  • Not correct: CREATE NONCLUSTERED INDEX IX_Orders_CustomerID ON Sales.Orders (CustomerID) WITH (DROP_EXISTING = ON);. This recreates the index with the same single key column and no included columns, so the query is still not covered and the Key Lookup remains.
  • Correct: CREATE NONCLUSTERED INDEX IX_Orders_CustomerID ON Sales.Orders (CustomerID) INCLUDE (OrderDate, TotalDue) WITH (DROP_EXISTING = ON);. OrderDate and TotalDue are only returned, so they belong as included columns; the index then covers the query and the Key Lookup is removed. DROP_EXISTING = ON lets you redefine the existing index without dropping it first.
  • Not correct: ALTER INDEX IX_Orders_CustomerID ON Sales.Orders REBUILD WITH (ONLINE = ON);. A rebuild keeps the same index definition, so OrderDate and TotalDue are still missing from the index and must still be fetched from the clustered index.
  • Not correct: CREATE NONCLUSTERED INDEX IX_Orders_CustomerID ON Sales.Orders (CustomerID ASC) INCLUDE (OrderDate, TotalDue) WITH (ONLINE = ON);. The definition would cover the query, but ONLINE = ON does not permit replacing an existing index with the same name. Replacing it in one statement requires DROP_EXISTING = ON.

Practise this topic until it's automatic.

Ten questions a day, every answer explained, and misses that come back until you beat them.

Start free