الانتقال إلى المحتوى
قواعد البياناتIndexing· 7 دقائق للقراءة

Column Order in a Composite Index Decides Which Queries It Helps

An index on (A, B) is sorted by A first, so it seeks on A, or on A and B, but a filter on B alone has to read the whole thing.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

The "my orders" screen got a composite index on (CustomerId, CreatedAt) and became instant. A month later, the operations dashboard that lists the orders placed on one day is slow, even though its execution plan shows that same index being used. In a test on SQL Server 2022 with 1,000,000 orders, the customer's query read 3 pages. The dashboard's query read 2,507: the whole index, from the first entry to the last.

The common misconception

The belief: an index on (A, B) indexes both columns, so it helps any query that filters on A, on B, or on both.

Part of it is true, which is what makes it convincing. The plan for the dashboard query really does name the index, and reading it beat reading the table: 2,507 pages against 12,072 for the full table, because the index holds three narrow columns instead of every column. PostgreSQL 18 can even use such an index without a condition on its first column, in some cases. So "it uses the index" looks confirmed. But "uses" covers two very different operations, and only one of them scales.

What actually happens

Sorted by the first column, then the second

A two-column B-tree index works like a phone book sorted by family name, then by first name. Finding every Smith is quick, and so is finding Jane Smith. Finding every Jane means reading every page, because the Janes are scattered across all the family names. Microsoft's index design guide uses that example: an index on LastName, FirstName helps WHERE LastName = 'Smith', but not a query that searches only on FirstName.

So the engine can do two things with the index. An goes down the tree straight to the first matching entry and reads only the matching range. An index scan reads every entry and checks the condition on each one. A plan that "uses the index" may be doing either.

A seek needs a prefix

PostgreSQL's docs state the exact rule for B-trees: equality conditions on the leading columns, plus an inequality on the first column that has no equality, limit the part of the index that's read. Conditions on columns further right are still checked inside the index, so they save visits to the table, but they don't shrink the range being read.

That gives a second rule, which Use The Index, Luke sums up as "index for equality first—then for ranges". Take "a customer's orders since a date". With (CustomerId, CreatedAt), the seek goes to that customer and that date and reads 9 entries, for 3 pages. With (CreatedAt, CustomerId), the seek starts at the date and reads every order placed after it, checking CustomerId on each: 1,190 pages for the same 9 rows. When both conditions are equalities, the order doesn't matter for that query: an exact match on both columns took 3 reads with either index. What decides the order then is which other queries the index must also serve.

The order also serves ORDER BY

A B-tree returns entries in its own order, and it can read them backward. WHERE CustomerId = @c ORDER BY CreatedAt DESC with TOP (10) read 3 pages on (CustomerId, CreatedAt), with no sort step. On (CreatedAt, CustomerId) it scanned backward through all recent orders until it had found 10 of that customer: 1,200 pages. PostgreSQL's docs add a detail for mixed directions: a plain (x, y) index can't produce ORDER BY x ASC, y DESC, but one defined as (x ASC, y DESC) can.

PostgreSQL 18's skip scan is narrower than it sounds

PostgreSQL 18 added : for an index on (x, y) and WHERE y = 7700, it can run one search per value of x. The docs are clear about when that pays off: only when x has so few distinct values that most of the index can be skipped. With many distinct values, the whole index has to be read, and the planner usually prefers a sequential scan of the table. A CustomerId with 50,000 values is the case it doesn't fix.

Here are the five query shapes from the test, with each index on its own (covered queries, so no lookups to the table):

Query shape(CustomerId, CreatedAt)(CreatedAt, CustomerId)
CustomerId = @cSeek, 3 readsFull index scan, 2,509 reads
CustomerId = @c AND CreatedAt >= @sinceSeek, 3 readsSeek on the date range, 1,190 reads
CustomerId = @c AND CreatedAt = @tSeek, 3 readsSeek, 3 reads
One day of CreatedAtFull index scan, 2,507 readsSeek, 7 reads
CustomerId = @c, newest 10Backward seek, 3 readsBackward scan, 1,200 reads

One index per leading column you filter on

SQL
-- One index, expected to serve both screensCREATE INDEX IX_Orders_Customer_Created    ON dbo.Orders (CustomerId, CreatedAt);-- Dashboard: the orders placed on one day.-- Tested: Index Scan of the whole index, 2,507 readsSELECT Id, CustomerId FROM dbo.OrdersWHERE CreatedAt >= @day AND CreatedAt < DATEADD(day, 1, @day);

The second index isn't free: as the previous article in this path showed, every index slows down every insert. Add it when the dashboard query runs often enough to pay for it. The flip side is that an index on (CustomerId) alone is usually redundant next to (CustomerId, CreatedAt), since any seek it can do, the wider index can do too.

How to apply it in your project

  1. List the query shapes per tableFor each frequent query, write down which columns it compares with =, which one with a range, and what it sorts by.
  2. Order the key columnsPut the equality columns first and the one range or sort column after them. Columns compared only for equality can go in any order, so pick the one that also lets other queries seek.
  3. Check the plan for seeksRun each query shape and confirm an Index Seek whose SeekPredicates cover the columns you expect, not an Index Scan with a Predicate.
  4. Remove redundant prefixesAn index whose columns are a leading prefix of another index, such as (CustomerId) next to (CustomerId, CreatedAt), usually adds write cost without making any read faster.

Key takeaways

  • A composite index is sorted by its first column, then the next, so it can seek only through a prefix of its columns.
  • A filter on the second column alone reads the whole index: 2,507 pages instead of 7 in the test, even though the plan named the index.
  • Index for equality first, then for ranges: the same 9 rows cost 3 reads with (CustomerId, CreatedAt) and 1,190 with the reverse.
  • Column order also decides whether ORDER BY with TOP can stop early or must scan.
  • PostgreSQL 18's skip scan helps only when the leading column has few distinct values; it doesn't replace a correctly ordered index.

📚 المصادر

  1. Multicolumn Indexes — PostgreSQL Documentation
  2. Index Architecture and Design Guide — SQL Server, Microsoft Learn
  3. Indexes and ORDER BY — PostgreSQL Documentation
  4. Concatenated Indexes — Use The Index, Luke
  5. Greater, Less and BETWEEN — Use The Index, Luke

التعليقات (0)