Search code examples
databasepostgresqlindexingb-tree-index

Should I have index with all Where-clause fields?


I have a table, like this:

CREATE TABLE films (
    title       varchar(40) NOT NULL,
    did         integer NOT NULL,
    date_prod   date,
    kind        varchar(10)
);

I have a index, like this:

CREATE INDEX films_title_kind_idx ON films (title, kind);

I have a query, like this:

SELECT title, did, kind, date_prod 
FROM films
WHERE title = 'title1' AND
      kind = 'kind2' AND
      did = 4;

Should I create index with 3 columns? Or current index films_title_kind_idx is enough?


Solution

  • Depends.

    A reasonable rule of thumb is that an index is useful if it always matches less than ten percent of the records. Assuming this is really a movie database, an index for title, kind or even just title will return a very small record set for further filtering. I can't be sure because I don't know what did is (probably not a good field name), but if it has many values, it would be reasonable to add it into the composite index.