For testing purposes you can force the use of the index by “disabling” sequential scans – best in your current session only:
SET enable_seqscan = OFF;
Do not use this on a productive server. Details in the manual here.
I quoted “disabling”, because you cannot actually disable sequential table scans. But any other available option is now preferable for Postgres. This will prove that the multicolumn index on (metric_id, t)
can be used – just not as effective as an index on the leading column.
You probably get better results by switching the order of columns in your PRIMARY KEY
(and the index used to implement it behind the curtains with it) to (t, metric_id)
. Or create an additional index with reversed columns like that.
- Is a composite index also good for queries on the first field?
You do not normally have to force better query plans by manual intervention. If setting enable_seqscan = OFF
leads to a much better plan, something is probably not right in your database. Consider this related answer:
- Keep PostgreSQL from sometimes choosing a bad query plan