Skip to the workspace
Pebellslearn by building
Creating Indexes  ›  Lesson

Compound Indexes and the ESR Rule

Compound 15 minA compound index sorts by several fields in order, serves queries on any leading prefix of those fields, and works best with equality fields first, then sort fields, then range fields.

mongodb / Compound Indexes and the ESR Rule

Explore each scene at your own pace.

01 · The rule

The rule

Compound Indexes and the ESR Rule

The genre page asks for classic books under 10, oldest first. Three fields are involved: one tested for equality, one for a range, one for sorting. A single-field index helps with one of them. A compound index can serve all three, but only if the fields are in the right order.

The rule

Equality, then Sort, then Range; queries use the index from the left.

db.books.createIndex({ genres: 1, year: 1, price: 1 })

A compound index is sorted by the first field, then by the second within each first value, and so on, like a phone book sorted by surname, then first name.

Prefix rule: the index serves queries on any leading prefix of its fields.

Query filters on Uses { genres, year, price }?
genres yes
genres and year yes
genres, year and price yes
year only not efficiently: year is not a prefix

Sort direction: an index { a: 1, b: -1 } serves sort({ a: 1, b: -1 }) and its exact reverse sort({ a: -1, b: 1 }), but not sort({ a: 1, b: 1 }).

ESR rule for choosing the order: Equality fields first, then Sort fields, then Range fields.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.