Sub topic 9
Expression indexes
This chapter assumes you can read basic EXPLAIN output and know how a B-tree index serves equality, range, and sort queries. It also assumes you have seen multicolumn and partial indexes in the earlier chapters. The examples use the orders and users tables from the running schema.
What an expression index stores
An ordinary index stores column values. An expression index stores the result of computing an expression from each row. Postgres evaluates the expression when a row is inserted or updated, and the result becomes the key in the B-tree.
This matters when a query filters on a computed value. Suppose you look up users by email without regard to case:
SELECT id FROM users WHERE lower(email) = '[email protected]';An index on email cannot help here. The index is ordered by the raw email text, and the query asks about lower(email). Those orderings differ, so Postgres has to read every row, compute lower(email), and compare. An index on the expression solves this:
CREATE INDEX users_lower_email_idx ON users (lower(email));The index entries are now sorted by lowercased email. The search is the same B-tree descent you already know, but the key is the computed value.
Trying it with data
A tiny table makes the planner choose a sequential scan whatever indexes exist, so load some rows first:
INSERT INTO users (email)
SELECT 'User' || g || '@Example.com'
FROM generate_series(1, 100000) AS g;
ANALYZE users;
CREATE INDEX users_lower_email_idx ON users (lower(email));
EXPLAIN
SELECT id FROM users WHERE lower(email) = '[email protected]';You should see an Index Scan or Bitmap Index Scan on users_lower_email_idx. If you run the EXPLAIN before creating the index, you get a Seq Scan with a filter on lower(email).
The query must use the same expression
The planner matches the query's expression against the index's expression. The match is structural. The planner does not reason about what the expression means.
| Query condition | Uses `users_lower_email_idx`? | Why |
|---|---|---|
| `WHERE lower(email) = 'x'` | Yes | Same expression, indexable operator |
| `WHERE email = 'x'` | No | The index holds `lower(email)`, not `email` |
| `WHERE email ILIKE 'x'` | No | The planner cannot rewrite `ILIKE` into `lower(email)` |
| `WHERE upper(email) = 'X'` | No | Different function |
The common failure is that the index exists and the query is almost the same, but it is not the same. Application code that sometimes writes lower(email) and sometimes email ILIKE gets the index only on some paths. Pick one form and use it everywhere. A view or a query-builder helper can enforce this.
Being a candidate does not guarantee use. As with any index, the planner estimates cost. A condition that matches most of the table will still get a sequential scan.
Syntax: when you need extra parentheses
A plain function call in the column list needs no extra parentheses, as in (lower(email)). Any other expression must be wrapped in its own parentheses. That includes operators, casts written with ::, and AT TIME ZONE. This is why the next example has so many:
CREATE INDEX orders_created_date_utc_idx
ON orders (((created_at AT TIME ZONE 'UTC')::date));
EXPLAIN
SELECT count(*)
FROM orders
WHERE (created_at AT TIME ZONE 'UTC')::date = DATE '2026-01-15';The outer pair of parentheses belongs to the column list. The next pair marks the expression. The inner pair is part of the expression itself. If you omit the middle pair, you get a syntax error.
This index supports "orders placed on a calendar day in UTC", a query that a plain index on created_at can only serve as a range (created_at >= ... AND created_at < ...). For a single day, the range form is often the better choice because it needs no extra index. An expression index pays off when the computed value is what you group, join, or compare on repeatedly.
Expressions must be immutable
Postgres only accepts an index expression whose functions are IMMUTABLE: given the same inputs, they always return the same result, forever. An index stores results computed at write time, so a function whose result can change would leave stale entries that no longer match what a query computes.
This is why the more obvious version of the date index fails:
-- Rejected: casting timestamptz to date depends on the session TimeZone setting.
CREATE INDEX orders_created_date_bad ON orders ((created_at::date));Postgres reports that functions in an index expression must be marked IMMUTABLE. The same timestamptz value is a different date in Tokyo than in Los Angeles, so the result depends on a session setting. Fixing the time zone with AT TIME ZONE 'UTC' turns the input into a plain timestamp, and the cast from timestamp to date is immutable. The next chapter covers immutability in more detail.
Unique expression indexes
An expression index can also be unique. This enforces uniqueness on the computed value:
CREATE UNIQUE INDEX users_email_ci_key ON users (lower(email));Now [email protected] and [email protected] collide, even though they are different strings. Inserting the second one fails with a unique violation.
You can combine this with a partial index so that soft-deleted users do not hold on to their address:
CREATE UNIQUE INDEX users_active_email_ci_key
ON users (lower(email))
WHERE deleted_at IS NULL;Queries that benefit must repeat both parts. They filter on lower(email) and include deleted_at IS NULL in the WHERE clause, so the planner can prove the query is covered by the index predicate.
If you already have users_active_email_key from the partial-index chapter, you do not need both. The case-insensitive one is stricter, and the plain one adds only write cost.
Costs and side effects
Expression indexes carry the usual index costs, with a few additions.
- Write cost. The expression is evaluated for every inserted row and for every update that could change its inputs. A cheap function like
lower()is negligible. An expensive immutable function slows every write to the table. - No HOT updates on the inputs. Postgres can skip index maintenance for "heap-only tuple" updates only when no indexed column changes. Updating
emailalways touches this index, becauseemailis one of its inputs. - Statistics.
ANALYZEcollects statistics on the expression's values, not just on the underlying column. This gives the planner good row estimates forlower(email) = ..., which an index on the raw column would not. RunANALYZEafter creating the index so the estimates exist. - Changing the definition. You cannot alter an index expression. You create a new index (see
CREATE INDEX CONCURRENTLYlater in this tutorial) and drop the old one.
Expression index or generated column?
Another way to get the same effect is a stored generated column with an ordinary index on it:
ALTER TABLE users
ADD COLUMN email_lower text GENERATED ALWAYS AS (lower(email)) STORED;
CREATE INDEX users_email_lower_col_idx ON users (email_lower);| Row | Expression index | Stored generated column + index |
|---|---|---|
| Extra table storage | None | One extra column per row |
| Query must write | The full expression | The column name |
| Value visible in `SELECT` | No | Yes |
| Adding it to a big table | Index build only | Rewrites the table (`ALTER TABLE` takes a long lock) |
Choose the expression index when the value is only needed for lookups. Choose the generated column when many queries, views, or application code need the computed value by name, or when you want to avoid the risk of mistyped expressions.
Checklist
- Write the query first, with the exact expression you will use everywhere.
- Create the index with that expression, adding the extra parentheses when it is not a plain function call.
- Run
ANALYZE, thenEXPLAINthe query and confirm the index name appears in the plan. - Try the near-miss forms (
email = ...,ILIKE) and confirm they do not use the index. This tells you which application paths need fixing.
Exercise
You create CREATE INDEX orders_created_date_idx ON orders (((created_at AT TIME ZONE 'UTC')::date));. A teammate writes SELECT count(*) FROM orders WHERE created_at::date = DATE '2026-01-15'; and finds that EXPLAIN shows a sequential scan on a large table. Give two reasons the index is not used, and say how to fix the query.
Show answer
First, the query's expression is created_at::date, which is not the same expression as (created_at AT TIME ZONE 'UTC')::date, so the planner does not consider the index. Second, created_at::date on a timestamptz depends on the session time zone, which is the same reason it could not be indexed at all. Rewrite the condition to use the indexed expression exactly: WHERE (created_at AT TIME ZONE 'UTC')::date = DATE '2026-01-15'. Run ANALYZE orders if the estimates still look wrong.
Exercise
You need case-insensitive email uniqueness among active users only. Write the index, and then write a lookup query that can use it.
Show answer
CREATE UNIQUE INDEX users_active_email_ci_key ON users (lower(email)) WHERE deleted_at IS NULL; A lookup that can use it is SELECT id FROM users WHERE lower(email) = '[email protected]' AND deleted_at IS NULL;. The query must contain both the same expression and a condition that implies the index predicate.