Search code examples
postgresqlindexing

Using INCLUDE with WHERE in PostgresSQL index


I have found usages of creating indexes with WHERE and INCLUDE operators at some project migrations. The index creation looks like:

CREATE INDEX CONCURRENTLY IF NOT EXISTS some_index 
ON some_table USING btree(some_column) 
INCLUDE (status)
WHERE status = 'Done';

And the query looks like this:

SELECT * FROM some_table WHERE status = 'Done' and some_column = 'abcd'

I think that INCLUDE operator has no sense here cause there is no filtration on status column and some_index will be applied without some filtration on column if we make query. So index without include will be as faster as index with this operator. May be there are some other reasons to use INCLUDE in partial index in such situation?


Solution

  • You use include when you want to perform index only scan. Index with include has ability to return the contents of non-key columns without having to visit the index's table

    In short when you want to leverage the benefit of index-only scan, whatever you put in Select has to be included in include

    In your case, instead of select *, use select status

    And yes, to answer your question for the query you have given, index without include will be faster