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.
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.
(CustomerId, OrderDate, Status) supports CustomerId = @c, CustomerId = @c AND OrderDate >= @d, but not OrderDate >= @d alone (that scans; SQL Server has no skip-scan).Trade-off: one well-ordered index can serve several queries; the wrong order serves none.
"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."
| 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 |
| 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 |
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.
Checks whether the candidate can predict seeks from index key order and design indexes from query patterns.
Green flags
Red flags
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.
In an actual execution plan an Index Seek shows two properties:
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.
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).
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.
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.
(A) is redundant if (A, B) exists (same leading column), unless (A) is unique or much narrower and hot. Consolidating reduces write cost.
dbo.Orders with 2 million rows and the index (CustomerId, OrderDate, Status).SET STATISTICS IO ON and record the logical reads.ORDER BY OrderDate DESC with TOP (20) and confirm there is no Sort.sys.index_columns.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; }
}
(OrderDate, CustomerId). Why it is wrong: after the range on OrderDate, CustomerId cannot narrow the seek. Instead: equality columns first, range last.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.(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.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 |
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.
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.
Last updated 23 Nov 2026.