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

📚 Interview question

You have a composite index on (CustomerId, OrderDate, Status) in SQL Server. Which queries can seek on it and which can't? Explain why column order matters, the leftmost-prefix rule, and how you decide the order of columns.

Covers how a composite B+ tree index is sorted, the leftmost-prefix rule, equality-then-range column ordering, which predicates give seeks versus scans, and when to create a second index instead.

Intermediate Theory Intermediate composite-index index-seek indexes query-performance sql-server t-sql

🎯 Key points

  • Composite index is sorted by the first column, then the second within it, and so on
  • Leftmost-prefix rule: a seek uses a contiguous run of leading columns, each with a predicate
  • Equality on every column before the range column; after a range, later columns are only residual predicates
  • Index on (A, B) returns rows in A, B order, and in B order for a single A value, avoiding a Sort
  • No skip-scan in SQL Server: WHERE B = @x alone scans an index led by A
  • Order by query patterns, with selectivity as a tie-breaker
  • Seek Predicates versus Predicate, and Rows Read versus Actual Rows, in the actual plan
  • Consolidate left-prefix duplicates instead of piling up overlapping indexes

⏱ 30-second answer

A composite index is a B+ tree sorted by the first column, then by the second within each first value, like a phone book sorted by surname then first name.

  • Leftmost-prefix rule: SQL Server can seek only when the query constrains the leading column(s). (CustomerId, OrderDate, Status) supports CustomerId = @c, CustomerId = @c AND OrderDate >= @d, but not OrderDate >= @d alone (that scans; SQL Server has no skip-scan).
  • Put equality columns first, then the range column. After a range, later columns can only be filtered as a residual predicate, not seeked.
  • The order also lets the index return rows already sorted, avoiding a Sort.

Trade-off: one well-ordered index can serve several queries; the wrong order serves none.

🗣 Full answer (senior)

How I would answer this in an interview

"A composite index is sorted by its first column, then by the second column within each value of the first, and so on. It's exactly a phone book: sorted by surname, then first name. You can find every 'Smith' quickly, and every 'Smith, John' quickly, but finding every 'John' means reading the whole book. That's the leftmost-prefix rule: SQL Server can only seek when the query gives it the leading column, and then each next column in order.

So for an index on CustomerId, OrderDate, Status: 'CustomerId = 42' seeks. 'CustomerId = 42 and OrderDate after the first of July' seeks to the start of that range and reads only it. 'CustomerId = 42 and Status = 3' seeks on CustomerId, but Status can't be part of the seek because OrderDate sits between them, so SQL Server reads all of customer 42's rows and filters Status as a residual predicate. And 'OrderDate after July' on its own scans the whole index, because SQL Server doesn't have the skip-scan some other databases have. The rule I use is equality columns first, then the one range or sort column, because anything after a range can't narrow the seek. If the query also says ORDER BY OrderDate, that order gives sorted rows for free and removes a Sort operator.

The mistake I see is ordering columns by selectivity alone, putting the 'most unique' column first regardless of the queries. Selectivity matters, but the query's predicates decide what can seek. I design composite indexes from the actual WHERE and ORDER BY clauses, then check the seek predicate in the actual plan."


Which queries seek on (CustomerId, OrderDate, Status)

Predicate Seek? Notes
CustomerId = @c Yes Prefix of 1
CustomerId = @c AND OrderDate >= @d Yes Seek on both, range on the second
CustomerId = @c AND OrderDate = @d AND Status = @s Yes Full key
CustomerId = @c AND Status = @s Partly Seek on CustomerId, Status is residual
CustomerId = @c AND OrderDate >= @d AND Status = @s Partly Status residual after the range
OrderDate >= @d No Index or table scan
CustomerId IN (1,2,3) Yes Three seeks

Ordering rules

Rule Why
Equality predicates first They keep the remaining columns sorted within one value
Then one range or ORDER BY column A range ends the seekable prefix
Most queried leading column A column no query filters on makes the index useless
Consider ORDER BY direction (CustomerId, OrderDate DESC) matches 'newest first' pages

Production example

A customer portal ran WHERE CustomerId = @c AND Status = 1 ORDER BY OrderDate DESC against an index on (OrderDate, CustomerId). Every call scanned about 60,000 pages. Recreating it as (CustomerId, Status, OrderDate DESC) gave a seek returning rows in order with no Sort: logical reads fell to 6 and p95 from 350 ms to 3 ms.

🔍 What the interviewer is checking

Checks whether the candidate can predict seeks from index key order and design indexes from query patterns.

Green flags

  • States the leftmost-prefix rule and equality-before-range
  • Knows SQL Server has no skip-scan
  • Mentions residual predicates and rows read vs actual rows
  • Uses index order to avoid a Sort

Red flags

  • "Put the most selective column first" as the only rule
  • Thinks any column of the index can be seeked
  • Creates one index per column

📚 Learn in depth

1. How a composite key is sorted

The index key is the concatenation of the columns, compared column by column:

(CustomerId, OrderDate, Status)
(41, 2026-03-01, 2)
(42, 2026-01-05, 1)   <- all rows for 42 are together...
(42, 2026-02-11, 3)   <- ...and sorted by OrderDate within 42
(42, 2026-07-02, 1)
(43, 2025-12-30, 2)

Within CustomerId 42 the rows are ordered by OrderDate, so a range on OrderDate is contiguous. Status is only sorted within a single (CustomerId, OrderDate) pair, so filtering Status across a date range is not contiguous.

2. Seek predicate versus residual predicate

In an actual execution plan an Index Seek shows two properties:

  • Seek Predicates: what positioned the seek (prefix columns and one range).
  • Predicate (residual): evaluated on every row the seek reads.
Index Seek IX_Orders_Cust_Date_Status
  Seek Predicates: CustomerId = 42 AND OrderDate >= '2026-07-01'
  Predicate:       Status = 3          <- filtered after reading
  Actual rows read: 1,840   Actual rows: 12

A big gap between Number of Rows Read and Actual Number of Rows means the index order is not ideal.

3. No skip-scan

Oracle and recent PostgreSQL versions can "skip scan" a leading column with few distinct values. SQL Server does not; a predicate on a non-leading column alone leads to a scan of that index (still maybe cheaper than the table if the index is narrow).

4. Ordering and sort avoidance

If the index order matches the query's ORDER BY after the equality columns, the plan has no Sort operator, and TOP (20) can stop after 20 rows. This is what makes keyset pagination cheap. SQL Server can also read an index backwards, so (CustomerId, OrderDate) serves ORDER BY OrderDate DESC for one customer; mixed directions (ORDER BY A ASC, B DESC) need the index declared that way.

5. Selectivity is the tie-breaker, not the rule

When two columns are both always used with equality, put the one other queries also use alone first, so the index serves more queries. Selectivity of the combined key is what the optimiser estimates via the multi-column density in the index statistics.

6. Overlapping indexes

(A) is redundant if (A, B) exists (same leading column), unless (A) is unique or much narrower and hot. Consolidating reduces write cost.

Try it yourself

  1. Build dbo.Orders with 2 million rows and the index (CustomerId, OrderDate, Status).
  2. Run the seven predicates from the table above with SET STATISTICS IO ON and record the logical reads.
  3. In each actual plan, compare Seek Predicates with Predicate and Rows Read with Actual Rows.
  4. Add ORDER BY OrderDate DESC with TOP (20) and confirm there is no Sort.
  5. Find redundant left-prefix indexes in a real database with a query over sys.index_columns.

💻 Code

An index ordered equality-first, range-last, and the queries it does and does not serve.

CREATE NONCLUSTERED INDEX IX_Orders_Customer_Status_Date
    ON dbo.Orders (CustomerId, Status, OrderDate DESC)
    INCLUDE (Total);

SET STATISTICS IO ON;

-- Seek on CustomerId and Status, rows already in OrderDate DESC order: no Sort, TOP stops early
SELECT TOP (20) OrderId, OrderDate, Total
FROM dbo.Orders
WHERE CustomerId = @CustomerId AND Status = 1
ORDER BY OrderDate DESC;

-- Seek on CustomerId only: Status is not given, so OrderDate cannot be part of the seek
SELECT OrderId, Total
FROM dbo.Orders
WHERE CustomerId = @CustomerId AND OrderDate >= '2026-07-01';

-- No leading column: scans the index (or uses another index)
SELECT COUNT(*) FROM dbo.Orders WHERE OrderDate >= '2026-07-01';
-- Find indexes whose key is a left prefix of another index on the same table
WITH k AS (
    SELECT ic.object_id, ic.index_id,
           STRING_AGG(CAST(ic.column_id AS varchar(10)), ',') WITHIN GROUP (ORDER BY ic.key_ordinal) AS cols
    FROM sys.index_columns AS ic
    WHERE ic.key_ordinal > 0
    GROUP BY ic.object_id, ic.index_id
)
SELECT OBJECT_NAME(a.object_id) AS table_name, ia.name AS redundant_candidate, ib.name AS wider_index
FROM k AS a
JOIN k AS b ON a.object_id = b.object_id AND a.index_id <> b.index_id
           AND b.cols LIKE a.cols + ',%'
JOIN sys.indexes AS ia ON ia.object_id = a.object_id AND ia.index_id = a.index_id
JOIN sys.indexes AS ib ON ib.object_id = b.object_id AND ib.index_id = b.index_id
WHERE OBJECTPROPERTY(a.object_id, 'IsUserTable') = 1 AND ia.is_unique = 0;

EF Core 10 declares column order with the order of the lambda members.

namespace Shop.Data;

using Microsoft.EntityFrameworkCore;

public sealed class ShopContext(DbContextOptions<ShopContext> options) : DbContext(options)
{
    public DbSet<Order> Orders => Set<Order>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Order>()
            .HasIndex(o => new { o.CustomerId, o.Status, o.OrderDate })
            .IsDescending(false, false, true)          // OrderDate DESC
            .IncludeProperties(o => o.Total)           // SQL Server provider extension
            .HasDatabaseName("IX_Orders_Customer_Status_Date");
    }
}

public sealed class Order
{
    public int OrderId { get; set; }
    public int CustomerId { get; set; }
    public byte Status { get; set; }
    public DateTime OrderDate { get; set; }
    public decimal Total { get; set; }
}

⚠ Common mistakes

  • Mistake: Putting the range column first, e.g. (OrderDate, CustomerId). Why it is wrong: after the range on OrderDate, CustomerId cannot narrow the seek. Instead: equality columns first, range last.
  • Mistake: Expecting WHERE Status = @s to seek on (CustomerId, Status). Why it is wrong: SQL Server has no skip-scan; the leading column is required. Instead: a separate index led by Status if that query matters.
  • Mistake: Ordering purely by selectivity. Why it is wrong: a highly selective column that queries do not filter on first makes the index unusable. Instead: order by the query predicates, use selectivity as a tie-breaker.
  • Mistake: Creating (A), (A, B) and (A, B, C) separately. Why it is wrong: three structures to maintain where one serves all three prefixes. Instead: keep the widest that is needed and drop left-prefix duplicates.
  • Mistake: Reading only "Index Seek" in the plan and stopping. Why it is wrong: a seek with a residual predicate can still read thousands of rows. Instead: compare Number of Rows Read with Actual Number of Rows.
  • Mistake: Forgetting ORDER BY direction. Why it is wrong: mixed ASC/DESC ordering cannot use an index declared all ASC, so a Sort appears. Instead: declare the index with matching directions.

🏛 Senior insight: trade-offs

Composite index design is query-pattern design. I list the top queries for a table (from Query Store, by executions times duration), write down each one's equality columns, range column and sort, and look for the smallest set of indexes whose prefixes cover them. Usually two or three well-ordered indexes replace six single-column ones.

Option When it fits Cost When not to
One composite index, equality-then-range Several queries share the leading columns One wider structure Queries filter on disjoint columns
Two narrower indexes Queries lead with different columns More writes, more memory A single prefix covers both
Index intersection (two single-column seeks) Rare ad-hoc combinations Extra join, usually slower Hot, frequent queries

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions avoiding a Sort with ORDER BY and TOP. Why: Checks they can use index order for keyset pagination.
    How to answer

    Skip(n) becomes OFFSET n ROWS, so SQL Server reads and discards n rows every time; page 5,000 reads 100,000 rows to return 20, and cost grows linearly with depth. Keyset paging remembers the last row's sort key and filters WHERE Price > @lastPrice OR (Price = @lastPrice AND Id > @lastId) with the same ORDER BY Price, Id, which seeks an index and reads only the rows it returns, so every page costs the same. It is also stable when rows are inserted. The trade-off: no jumping to page N, so it suits infinite scroll, APIs and exports, while offset stays fine for shallow, numbered pages in admin screens. The sort key needs a matching index and a unique tiebreaker.

  2. When: Candidate explains why the tree is sorted column by column. Why: Checks the underlying B-tree knowledge.
    How to answer

    A tree is a hierarchy of nodes with one root, where each node has children and no cycles. A binary tree limits each node to two children (left, right). A binary search tree (BST) adds an ordering rule: left subtree < node < right subtree, so search, insert and delete take O(height).

    If the tree is balanced, height is O(log n); if you insert sorted data into a plain BST it degenerates into a linked list with O(n) height. Self-balancing trees (red-black, AVL) keep O(log n); .NET's SortedSet and SortedDictionary are red-black trees.

    Traversals: in-order (sorted output for a BST), pre-order (copy/serialise), post-order (delete/evaluate), level-order (BFS).

    Trees are everywhere: database B+ tree indexes, file systems, JSON/XML/DOM, Roslyn syntax trees, expression trees, org charts.

↩ Usually asked after

More in Indexes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me