Expression index

Also known as: function-based index

On this page 7

An expression index is a database index built on the computed result of an expression or function applied to one or more columns, rather than on the raw column values. In indexing for relational databases, it lets the query planner answer predicates such as lower(email) = 'ana@example.com' with an index lookup instead of a full table scan. The concept is also called a function-based index, the term Oracle uses, while PostgreSQL calls it an index on expressions.

The value of an expression index lies in a simple rule: an ordinary index helps only when the query compares the indexed value itself. Once a column is wrapped in a function, a cast or an arithmetic operation, a plain index on that column becomes useless for the predicate, and the expression index closes that gap.

How an expression index stores computed keys

An expression index evaluates its expression once per row at write time and stores the result as the index key, together with a pointer to the row. The underlying structure is usually a B-tree, although PostgreSQL also allows hash, GiST, GIN and other access methods over expressions. Reads then become cheap, because the database compares the search value with precomputed keys instead of computing the function for every row.

The planner uses the index only when the query contains an expression that matches the indexed expression after normalization. Matching is structural, not semantic: lower(email) in the index will not serve a query written as upper(email), even though both normalize case. This is the most frequent reason why a newly created expression index appears to be ignored.

The following table shows typical expressions and the queries they accelerate.

Indexed expressionQuery predicate it servesTypical purpose
lower(email)WHERE lower(email) = $1Case-insensitive lookup
date_trunc('day', created_at)WHERE date_trunc('day', created_at) = $1Grouping by calendar day
(price * quantity)WHERE price * quantity > 1000Filtering on derived totals
(data->>'customer_id')WHERE data->>'customer_id' = $1Lookup inside JSON documents
substr(code, 1, 3)WHERE substr(code, 1, 3) = 'EUR'Prefix extraction
Common expression index patterns

Requirements for the indexed expression

The indexed expression must be deterministic: for the same input it must always return the same output. PostgreSQL enforces this by accepting only functions marked IMMUTABLE, Oracle requires the DETERMINISTIC keyword on user-defined functions, and SQL Server requires a persisted computed column with deterministic, precise logic. A function that depends on the current time, session settings or another table would produce stale index keys and therefore wrong query results.

Implementations differ in syntax and in how the expression is exposed, as the following comparison shows.

Database systemMechanismKey restriction
PostgreSQLCREATE INDEX ... ON t ((expr))Functions must be IMMUTABLE
Oracle DatabaseFunction-based indexUser functions must be DETERMINISTIC
MySQL 8.0.13+Functional key partImplemented as a hidden virtual column
SQL ServerIndex on a computed columnColumn must be deterministic and precise
SQLite 3.9+Index on expressionsOnly deterministic functions allowed
Expression index support across database systems

A classic trap concerns time zones and collations. Casting a timestamptz value to date depends on the session time zone, so PostgreSQL rejects it as non-immutable. Developers who wrap such a cast in a function falsely labeled IMMUTABLE silently create an index that can return incorrect rows when the session setting changes.

An expression index solves a different problem from its neighbors in the indexing toolbox: it changes what value is indexed, whereas other types change which rows are indexed or which columns are included. The types can also be combined, for example a partial expression index or a composite index with one expression key and one plain column.

Index typeWhat it changesWhen it fits better
Expression indexThe indexed valuePredicates wrap a column in a function
Partial indexThe set of indexed rowsQueries target a small, fixed subset
Composite indexThe number of key columnsPredicates combine several raw columns
Covering indexColumns stored in the leafAvoiding table access for selected columns
Generated column with indexValue stored in the tableThe derived value is also read or exposed
How an expression index differs from neighboring concepts

The generated column alternative deserves attention. Storing the computed value as a real column makes it visible to applications, simplifies query writing and lets statistics be gathered like any other column, at the cost of extra table storage. An expression index keeps the table unchanged but requires every query to repeat the exact expression.

When to create an expression index

Create an expression index when a frequent, selective query filters, joins or sorts on a derived value and rewriting the query to use the raw column is impractical. Case-insensitive identifiers, JSON attribute lookups and normalized codes are the most common cases. The decision table below summarizes typical situations.

SituationRecommended choiceReason
Login by email, any letter caseIndex on lower(email)Matches the normalized comparison
Range filter on created_atPlain index plus range rewritecreated_at >= d AND < d + 1 uses the raw column
Frequent JSON key lookupsExpression index on the keyAvoids scanning whole documents
Derived value shown in reportsGenerated column with indexValue is reused beyond filtering
Rare ad hoc analysis queryNo new indexWrite cost outweighs occasional benefit
Choosing between an expression index and alternatives

Before creating one, check that a sargable rewrite is not simpler. A predicate such as WHERE year(order_date) = 2025 can be rewritten as a date range on the raw column, which an existing B-tree index already serves without any additional write overhead.

Costs, statistics and common mistakes

Every insert and every update of a referenced column forces the database to evaluate the expression again and maintain the index entry. With cheap functions such as lower() the overhead is minor, but an expensive user-defined function can noticeably slow write-heavy workloads. The index also consumes storage proportional to the size of the computed keys.

Expression indexes carry a useful side effect: PostgreSQL gathers statistics on the indexed expression during ANALYZE, which improves row estimates for queries that use it. Without such statistics, the planner guesses selectivity for function calls and may choose a poor plan even when the index exists.

  • Expression mismatch: the query writes LOWER(TRIM(email)) while the index covers only lower(email).
  • Implicit type casts: comparing a text expression with a numeric parameter adds a cast that breaks matching.
  • Collation differences: a query using another collation cannot use an index built under the default one.
  • Mislabeled functions: declaring a volatile function immutable causes silent wrong results.
  • Unverified plans: always confirm usage with EXPLAIN rather than assuming the index is chosen.

The simple explanation

A normal index is like an alphabetical list of names in a phone book. If you search for a name exactly as it is printed, you find it fast. If you want to search for a name regardless of capital letters, the printed list no longer helps, and you would have to read every entry.

An expression index is a second list prepared in advance with every name already converted, for example to lowercase. The database builds and updates this list automatically whenever data changes. The search then stays fast, as long as the question is asked in exactly the same converted form.

How it is used in practice

An online retailer stores about 12 million customer accounts in PostgreSQL. Customers sign in with their email address, typed in any mix of capital letters, so the login query compares lower(email) with the lowercased input. The existing unique index on email cannot serve this predicate, and every login performs a sequential scan that takes roughly 900 milliseconds at peak traffic.

The database team creates a unique expression index on lower(email) with CREATE INDEX CONCURRENTLY, which avoids blocking writes during the build. After ANALYZE, EXPLAIN shows an index scan, and login lookups drop to under one millisecond. The unique constraint on the lowercased value also prevents two accounts that differ only in letter case, which removes a long-standing source of duplicate customer records.