PostgreSQL provides several index types: B-tree, Hash, GiST, SP-GiST, GIN, BRIN, and the extension bloom. Each index type uses a different algorithm that is best suited to different types of indexable clauses. By default, the CREATE INDEX
command creates B-tree indexes, which fit the most common situations. The other index types are selected by writing the keyword USING
followed by the index type name. For example, to create a Hash index:
CREATE INDEXname
ONtable
USING HASH (column
);
B-trees can handle equality and range queries on data that can be sorted into some ordering. In particular, the PostgreSQL query planner will consider using a B-tree index whenever an indexed column is involved in a comparison using one of these operators:
< <= = >= >
Constructs equivalent to combinations of these operators, such as BETWEEN
and IN
, can also be implemented with a B-tree index search. Also, an IS NULL
or IS NOT NULL
condition on an index column can be used with a B-tree index.
The optimizer can also use a B-tree index for queries involving the pattern matching operators LIKE
and ~
if the pattern is a constant and is anchored to the beginning of the string — for example, col LIKE 'foo%'
or col ~ '^foo'
, but not col LIKE '%bar'
. However, if your database does not use the C locale you will need to create the index with a special operator class to support indexing of pattern-matching queries; see Section 11.10 below. It is also possible to use B-tree indexes for ILIKE
and ~*
, but only if the pattern starts with non-alphabetic characters, i.e., characters that are not affected by upper/lower case conversion.
B-tree indexes can also be used to retrieve data in sorted order. This is not always faster than a simple scan and sort, but it is often helpful.