I have a Rails app on a Postgres database which relies heavily on queries like this:
SELECT DISTINCT client_id FROM orders WHERE orders.total>100
I need, essentially, the ids of all the clients who have orders which meet a certain condition. I only need the id, so I figured this is way faster than using joins.
Would I benefit from adding an index to the column “total”? I don’t mind insert speed, I just need the query to run extremely fast.
I would expect the following multicolumn index to be fastest:
PostgreSQL 9.2 could benefit even more. With it’s “index-only tuples” feature, it could serve the query without hitting the table under favorable circumstances: no writes since the last
VACUUM.DESCorASChardly matters in this case. A B-tree index can be searched in both directions almost equally efficient.