Using Ordered Lookup to Answer a Range Query

An index with compatible ordering can make it possible to find the beginning of a range and scan relevant entries.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a time window
  2. Check which keys come first
  3. Relate a range predicate to consecutive keys
  4. Include equality prefixes for composite keys when appropriate

Trace a time window

A query about dates from start through before end can begin at the earliest matching date in a suitable ordered structure. Sorted range queries explain that model.

Check which keys come first

An index organized first by category supplies a date order within each category. A query about all categories may need another arrangement. See composite prefixes.[1]

Relate a range predicate to consecutive keys

A sorted index with keys two, four, seven and nine can find the first key at least four and continue until reaching nine for range \([4,9)\). A matching ordered index can help avoid sorting in some query plans. See range selection from sorted records.

Ordered keys: 2,4,7,9
Lower bound 4 → begin at 4
Stop before 9
Returned: 4 and 7

Include equality prefixes for composite keys when appropriate

With keys account and time, one account occupies a contiguous region if that is the leading key. Queries across every account may need a different plan. Test narrow and broad ranges with actual query plans.

References

  1. PostgreSQL Global Development Group, Concurrency Control ↩