Sub topic 9
Indexing a Generated Column
This chapter assumes you can write CREATE TABLE and CREATE INDEX, and that you can read basic EXPLAIN output. It also assumes you know that a B-tree index lets PostgreSQL find rows without scanning the whole table. You should already know how to define a stored generated column.
Why index a generated column
A generated column is often created to answer a question the raw columns answer awkwardly. Examples are "which customer has this email, ignoring case?" and "which person is called Ada King?". Those questions become WHERE clauses, and on a large table a WHERE clause without an index means a sequential scan.
A stored generated column holds a real value in the table's heap, the same as any ordinary column. An index only needs a value to store, so you create it the same way:
CREATE INDEX people_full_name_idx ON people (full_name);
SELECT id FROM people WHERE full_name = 'Ada King';PostgreSQL does not treat the column specially here. The index is a normal B-tree over the stored values, and the planner uses it like any other index. The differences from an ordinary column appear when rows are written, because you cannot write to the column yourself.
A worked example
This script is self-contained. It builds a table of customers whose emails are compared case-insensitively. It then enforces uniqueness on the normalized form and checks that the planner uses the index.
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
email_norm text GENERATED ALWAYS AS (lower(email)) STORED
);
INSERT INTO customers (email)
SELECT 'User' || g || '@Example.com'
FROM generate_series(1, 100000) AS g;
CREATE UNIQUE INDEX customers_email_norm_key ON customers (email_norm);
ANALYZE customers;
EXPLAIN
SELECT id FROM customers WHERE email_norm = '[email protected]';The plan has this shape. Your cost numbers will differ.
Index Scan using customers_email_norm_key on customers (cost=0.42..8.44 rows=1 width=8)
Index Cond: (email_norm = '[email protected]'::text)The index also protects the data. Inserting [email protected] now fails with a unique violation. The application cannot forget to normalize the email, because the database does it.
The sequence for each write looks like this:
The planner matches columns, not expressions
The planner does not know that email_norm is defined as lower(email). It matches your query against the index by column. These two queries look equivalent but behave differently:
-- Can use customers_email_norm_key
SELECT id FROM customers WHERE email_norm = '[email protected]';
-- Cannot use it: the index is on email_norm, and the query filters on lower(email)
SELECT id FROM customers WHERE lower(email) = '[email protected]';The second query falls back to a sequential scan unless you also have an expression index on lower(email). Queries must name the generated column. This is the main practical change when you adopt one. Review the application's queries, or put a view in front of the table so that callers use the right column.
Uniqueness and other constraints
Because the value is stored, a generated column can back a unique index, as shown above. You can also declare the constraint form:
ALTER TABLE customers
ADD CONSTRAINT customers_email_norm_uniq UNIQUE (email_norm);A CHECK constraint on a generated column is also allowed. It is evaluated against the computed value, so it can enforce a rule on a derived result:
ALTER TABLE customers
ADD CONSTRAINT email_norm_not_empty CHECK (length(email_norm) > 0);Foreign keys have restrictions. In particular, a stored generated column used as a referencing column cannot use the ON UPDATE CASCADE, SET NULL, or SET DEFAULT actions. The Limitations chapter covers these.
Index variants that work well
Any index feature that works on an ordinary column works on a stored generated column. Three are especially useful.
A partial index shrinks the index by covering only the rows you query:
CREATE INDEX customers_active_email_norm_idx
ON customers (email_norm)
WHERE email_norm LIKE '%@example.com';A multicolumn index can mix generated and ordinary columns:
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant_id integer NOT NULL,
unit_price numeric(10,2) NOT NULL,
quantity integer NOT NULL,
total numeric(12,2) GENERATED ALWAYS AS (unit_price * quantity) STORED
);
CREATE INDEX orders_tenant_total_idx ON orders (tenant_id, total);A covering index uses INCLUDE to carry extra columns so that an index-only scan can answer the query:
CREATE INDEX orders_total_covering_idx ON orders (total) INCLUDE (tenant_id);PostgreSQL also collects planner statistics for a stored generated column, the same as for any other column. Run ANALYZE after bulk loads so row estimates for WHERE total > 1000 are realistic.
Write cost
An index on a generated column adds work to every write that changes the source columns. When you run UPDATE customers SET email = '[email protected]' WHERE id = 7, PostgreSQL does the following:
- It sees that
emailchanged, so it recomputesemail_norm. - It writes a new row version.
- It adds a new entry to every index whose value changed, including the unique index on
email_norm.
An update that touches only unrelated columns does not change the generated value. PostgreSQL can often still use a heap-only tuple (HOT) update in that case, which skips new index entries. Updating a source column of an indexed generated column usually changes the indexed value and rules out HOT for that update. If a table has heavy updates on the source columns, the index adds real write cost. Measure it before indexing every derived column.
Generated column or expression index
An expression index can give you the same lookup without a new column:
CREATE INDEX customers_lower_email_idx ON customers (lower(email));
SELECT id FROM customers WHERE lower(email) = '[email protected]';Both approaches support unique enforcement and partial indexes. They differ in these ways:
| Aspect | Stored generated column + index | Expression index only |
|---|---|---|
| Heap storage | Value stored in every row | No extra heap storage |
| Index storage | One entry per row | One entry per row |
| Query must use | The generated column name | The exact indexed expression |
| Value visible in `SELECT *` | Yes | No |
| Reusable in `ORDER BY`, joins, views | Yes, by name | Only by repeating the expression |
| Change the expression later | Needs a table rewrite or column rebuild | Build a new index, drop the old one |
Choose the generated column when many queries, views, or applications need the derived value by name, or when you want it visible in results. Choose the expression index when the value serves only one lookup pattern and you want to avoid storing it in the heap.
Virtual generated columns
PostgreSQL 18 adds virtual generated columns, which take no storage and are computed when read. Because no value exists on disk, they do not fit B-tree indexes the way stored columns do. In PostgreSQL 18, you cannot create an index on a virtual generated column, and an expression index that references one is also unsupported. If you need an index, declare the column STORED, or index the underlying expression directly on the base columns.
Building indexes on large tables
A plain CREATE INDEX blocks writes to the table while it builds. On a busy table, use the concurrent form:
CREATE INDEX CONCURRENTLY customers_email_norm_idx2
ON customers (email_norm);CREATE INDEX CONCURRENTLY cannot run inside a transaction block. If it fails, it can leave an invalid index that you must drop and retry. This applies to ordinary columns too, but generated columns make it more relevant. Adding a stored generated column to an existing table rewrites the table, so large migrations usually add the column in one step and index it concurrently in another.
Checking that the index is used
Follow these steps when a query on a generated column is still slow:
- Confirm the query filters on the generated column, not the original expression.
- Run
ANALYZEon the table so statistics exist. - Run
EXPLAINand look for anIndex ScanorBitmap Index Scanon your index. - Confirm the comparison type matches. For text columns with a non-default collation, the index must use the same collation as the query.
- On a tiny table, a sequential scan can be correct, because reading a few pages is cheaper than using an index. Test with realistic row counts.
Common errors
- Writing a value into the column.
INSERT ... (email_norm) VALUES (...)fails, because onlyDEFAULTis accepted. Leave the column out of the column list. - Querying the source expression.
WHERE lower(email) = ...does not use an index onemail_norm. Use the generated column name or add an expression index. - Expecting an index on a virtual column. This is unsupported in PostgreSQL 18, as above.
- Indexing a non-immutable expression. The failure happens earlier, when the generation expression is rejected at table creation, as the chapter on expression rules showed.
Exercise
A table invoices has net numeric(10,2), tax_rate numeric(4,3), and a stored generated column gross numeric(12,2) GENERATED ALWAYS AS (net * (1 + tax_rate)) STORED with an index on gross. A developer runs SELECT id FROM invoices WHERE net * (1 + tax_rate) > 1000 and finds that the index is not used. Why, and what are two ways to fix it?
Show answer
The planner matches indexes to columns and index expressions, and it does not recognize that gross is defined by net * (1 + tax_rate). The query therefore sees no usable index. Fix 1: rewrite the query as WHERE gross > 1000. Fix 2: create an expression index on (net * (1 + tax_rate)), so the query's expression matches the index. The first fix is simpler, since the index already exists.
Exercise
You want to enforce that no two customers share an email address that differs only by letter case, and you are on PostgreSQL 18. You consider making email_norm a VIRTUAL generated column to save disk space. Does this work with a unique index on email_norm, and what do you do?
Show answer
No. PostgreSQL 18 does not support indexes on virtual generated columns, so a unique index on a virtual email_norm cannot be created. Either declare email_norm as STORED and create the unique index on it, or skip the column and create a unique expression index directly: CREATE UNIQUE INDEX ON customers (lower(email));. Both enforce case-insensitive uniqueness. The stored column also keeps the normalized value visible and queryable by name.