2

I have the following code:

SELECT * FROM table WHERE column1='value1' AND column2='value2';

I have an index for column1 and another for column2.

How do I tell Postgres to prefer the second index? Should I put it first?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228

1 Answers1

2

You cannot tell Postgres directly which index to prefer. It wouldn't make sense, either, except for rare corner cases.

  • The order of expressions in the WHERE clause is completely irrelevant. The query planner will apply predicates as it sees fit.

  • You are not limited to use just one index. Postgres can use both an combine them with bitmap index scans. Details in this related answer on dba.SE:

    But its often more effective to use just one index and filter the rest.

  • Finally, you can create a single multicolumn index over both columns for optimized performance. Like:

    CREATE INDEX foo ON tbl (column1, column2);
    

    Or even a partial index if one of your predicates is constant (most or all queries restrict to column2 = 'constant_value') and this selection is substantially smaller than the whole table:

    CREATE INDEX foo ON tbl (column1) WHERE column2 = 'constant_value';
    

If Postgres makes bad choices for query plans, there is typically something off in your database:

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
  • Thanks for the answer! My problem is that i have a big OR for column1: SELECT * FROM table WHERE (column1='value1' OR column1='value3' OR ...) AND column2='value2'; an also, my column2 is UNIQUE... If i do an index on both columns i dont want postgres to look for all the combinations, like: column1 = 'value1' AND column2='value2' column1 = 'value3' AND column2='value2' .... Thank you anyway, now i know that i cant priorize indexes, i will put two indexes and trust the postgres power – Guido Sofer Inglesi Nov 04 '14 at 17:21
  • @GuidoSoferInglesi: Well, that's quite a different question then. I suppose you start a *new question* that has all the necessary details, including the table definition with existing indexes, your query, your version of Postgres and the output of `EXPLAIN ANALYZE`. There may be room for optimization. – Erwin Brandstetter Nov 04 '14 at 20:49