in postgres I will be doing 2 kinds of lookups. first one is by "userId" and second is by "userId" and "abortScript" together.
should i create 2 separate indexes for these columns like this
CREATE INDEX "Category_userId_idx" ON "Category"("userId");
CREATE INDEX "Category_abortScript_idx" ON "Category"("abortScript");
or should i create 1 composite index
CREATE INDEX "Category_userId_abortScript_idx" ON "Category"("userId", "abortScript");
please explain me why.
3
Answers
A single composite index like you describe is the best choice. It can also be used by queries that only have the first column in the
WHERE
condition.Without additional details, it’s impossible to give a definative answer. If there isn’t a need to query efficiently by
abortscript
independently ofuserid
, then most likely there shouldn’t be an index on justabortscript
because doing so would increase the amount of work required for insert, update, and delete operations but would likely not improve query performance. An index on justuserid
might perform better than a composite or covering index that includesabortscript
because approximately twice as many rows would appear in each block of the index which could result in less I/O activity.Benchmark each option against live data with realistic queries to determine which works best.
Depending on the mix of queries with the predicate columns you may want to create the composite index and an individual index on the second column of the composite index. So:
As @JohnH said "Benchmark each option against live data with realistic queries to determine which works best".