Postgresql – Postgres primary key sorted in the reverse order. Will it use the index efficiently

indexpostgresqlprimary-keysorting

My Rails database is backed by Postgres database. As you may know, each table in Rails gets assigned a primary key which is of Integer type and is indexed.

My list views show records in the reverse chronological order. So I just sort my result set in the reverse order of the primary key.

My question is: will the query use the primary key index? And if yes then as efficiently? How do I verify that?

Thanks in advance for your time.

Bharat

Best Answer

Indexes are typically unidirectional. This allows improvements in space and index scanning speed as back links don't need to be maintained. As @a_horse_with_no_name has noted, Postgres can and will be used to search in the reverse order to the index. (If this was not a unique index with no NULLs, positioning of NULLS FIRST/LAST could be a consideration.) Performance may not be as fast as using a non-standard index ordering, and the documentation notes significant speedups can be obtained with non-standard orderings.

For systems that don't support scanning indexes backwards, if your index is ascending, it would not be used for your query. There are two options in this case:

  • add another index with DESC specified; or
  • replace the primary key index with one which is has DESC specified. (I haven't tried this, and likely wouldn't as it breaks my expectations for primary keys.)