PostgreSQL 8.0.1 Documentation | ||||
---|---|---|---|---|
Prev | Fast Backward | Chapter 11. Indexes | Fast Forward | Next |
11.5. Indexes on Expressions
An index column need not be just a column of the underlying table, but can be a function or scalar expression computed from one or more columns of the table. This feature is useful to obtain fast access to tables based on the results of computations.
For example, a common way to do case-insensitive comparisons is to use the lower
function:
This query can use an index, if one has been defined on the result of the lower(col1) operation:
If we were to declare this index UNIQUE, it would prevent creation of rows whose col1 values differ only in case, as well as rows whose col1 values are actually identical. Thus, indexes on expressions can be used to enforce constraints that are not definable as simple unique constraints.
As another example, if one often does queries like this:
then it might be worth creating an index like this:
The syntax of the CREATE INDEX command normally requires writing parentheses around index expressions, as shown in the second example. The parentheses may be omitted when the expression is just a function call, as in the first example.
Index expressions are relatively expensive to maintain, since the derived expression(s) must be computed for each row upon insertion or whenever it is updated. Therefore they should be used only when queries that can use the index are very frequent.