Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 17 / Topic 4 of 8

Expression indexes

The classic production mystery: emails are stored mixed-case, the login query normalises — and the email index sits unused:

EXPLAIN (COSTS OFF)
SELECT * FROM big_users WHERE lower(email) = '[email protected]';
                       QUERY PLAN                       
--------------------------------------------------------
 Seq Scan on big_users
   Filter: (lower(email) = '[email protected]'::text)
(2 rows)

Seq scan, despite idx_users_email — the index sorts email, the query asks about lower(email), a different expression. The index must match what the query actually computes:

CREATE INDEX idx_users_email_lower ON big_users (lower(email));
ANALYZE big_users;
EXPLAIN (COSTS OFF)
SELECT * FROM big_users WHERE lower(email) = '[email protected]';
CREATE INDEX
ANALYZE
                         QUERY PLAN                         
------------------------------------------------------------
 Index Scan using idx_users_email_lower on big_users
   Index Cond: (lower(email) = '[email protected]'::text)
(2 rows)

Any immutable expression works — date_trunc('month', created_at), (payload ->> 'sku') — the rule is always the same: the indexed expression and the queried expression must be textually the same thing. (The other cure is normalising at write time — a citext column or Part 10's generated column — so the query needs no function at all. Both are honest; pick one and be consistent.)

🧪 Quick quiz — answer from memory, then check.

  1. Why did the plain email index not serve lower(email) = ...?
  2. Two fixes?
Show the answers
  1. The index orders raw email values; the query filters on a function's result — a value the index never stored.
  2. An expression index on lower(email), or storing normalised data (generated column / citext) so the query stops transforming.

Done here? The practice set for Part 17 — 5 exercises with solutions — is on the part page.

Search the guide