6. The ESR Guideline: Equality, Sort, Range

The ESR guideline is a practical way to reason about compound-index field order:

  • Equality: fields matched with equality predicates often belong first.
  • Sort: fields used to order results may follow.
  • Range: range predicates often come after equality and sort fields when preserving index-supported sorting is important.

For example, a query that filters on exact status, sorts by creation time, and applies a date range may need careful index design. The best order depends on the exact query, selectivity, and whether avoiding an in-memory sort or narrowing the range is more important.

ESR is a guideline, not a mechanical rule. A highly selective range can sometimes justify a different order. Test realistic data and examine execution plans before settling on an index.

Use ESR as a starting point

Index design is workload-specific. Compare candidate indexes with real filters, sort requirements, data distributions, and explain results.

Code Example
db.orders.createIndex({ status: 1, createdAt: -1 });

db.orders.find({ status: "delivered" })
  .sort({ createdAt: -1 })
  .limit(50)
  .explain("executionStats");
Key Takeaways
  • ESR stands for Equality, Sort, Range.
  • Equality fields often lead compound indexes.
  • Sort and range ordering depends on the workload.
  • ESR is a design heuristic rather than a universal law.
Knowledge Check

What does ESR stand for?