Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
QA interview question
Databases, SQL & BIDatabase conceptSeniorCommonTheory

Why does column order matter in a composite database index?

Answer

A multi-column index is ordered by its key sequence, so predicates and sorting that use the leading columns usually benefit most, while a condition only on a later column may not use it efficiently. Selectivity, range predicates, equality predicates, requested ordering and database-specific optimizer behaviour all influence the result. Verify several realistic query shapes with representative distributions and plans, and also measure write overhead before adding overlapping indexes.

Strong answer includes

  • understands leading-column behaviour
  • considers predicates, ordering and selectivity
  • validates with plans and write-cost measurements

Practical example

Leading-column behavior of a composite index
Dialect · Portable SQLRuntime · SQLite sample DB

Runs against the resettable SQLite sample database used by the playground.

SQL
SQLite · sample DB · browser sandbox
Result
Run the query to see the result.

The index is ordered first by customer_id, then status, then created_at. Queries that constrain the leading key sequence usually benefit more than a query that only filters a later column.

Expected result: Different plans for the two query shapes, verified with representative data rather than assumed from index existence.

#database#sql#composite-index#performance

Sources

PostgreSQL documentationPostgreSQL Global Development Group · Relational modelling, SQL, joins, constraints, transactions, concurrency, indexes, query plans and recovery