NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior1 view

What is a composite index, what is the main principle behind how it works, and how do you choose which fields to include?

Practice

Asked at

AI answer

A composite index is an index on multiple columns, for example, INDEX (status, created_at). The order of the columns matters: a DBMS can usually use this index efficiently for queries on its leftmost prefix (status or status, created_at), but not for queries on created_at alone. Therefore, choose columns based on actual WHERE conditions, joins, and sorts; columns checked for equality are often placed before a range column. Consider selectivity, query frequency, and the cost of the index: it takes up space and slows down inserts and updates. Verify the decision using the query execution plan.