PostgreSQL 8.0.1 Documentation | ||||
---|---|---|---|---|
Prev | Fast Backward | Chapter 11. Indexes | Fast Forward | Next |
11.3. Multicolumn Indexes
An index can be defined on more than one column. For example, if you have a table of this form:
(say, you keep your /dev directory in a database...) and you frequently make queries like
then it may be appropriate to define an index on the columns major and minor together, e.g.,
Currently, only the B-tree and GiST implementations support multicolumn indexes. Up to 32 columns may be specified. (This limit can be altered when building PostgreSQL; see the file pg_config_manual.h.)
The query planner can use a multicolumn index for queries that involve the leftmost column in the index definition plus any number of columns listed to the right of it, without a gap. For example, an index on (a, b, c) can be used in queries involving all of a, b, and c, or in queries involving both a and b, or in queries involving only a, but not in other combinations. (In a query involving a and c the planner could choose to use the index for a, while treating c like an ordinary unindexed column.) Of course, each column must be used with operators appropriate to the index type; clauses that involve other operators will not be considered.
Multicolumn indexes can only be used if the clauses involving the indexed columns are joined with AND. For instance,
cannot make use of the index test2_mm_idx defined above to look up both columns. (It can be used to look up only the major column, however.)
Multicolumn indexes should be used sparingly. Most of the time, an index on a single column is sufficient and saves space and time. Indexes with more than three columns are unlikely to be helpful unless the usage of the table is extremely stylized.