Sub topic 9
Indexing a Generated Column
This chapter assumes that you know basic CREATE TABLE, SELECT, and CREATE INDEX syntax. It also assumes that you know a stored generated column is calculated when a row is written and saved in the table.
A stored generated column can have an index just like an ordinary column. This is useful when the derived value appears often in WHERE, JOIN, or ORDER BY clauses.
Create and index a generated column
Suppose an application searches people by their complete name. The application could build the name in every query, but a generated column keeps the rule in the database:
CREATE TABLE people (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
first_name text NOT NULL,
last_name text NOT NULL,
full_name text GENERATED ALWAYS AS
(first_name || ' ' || last_name) STORED
);
INSERT INTO people (first_name, last_name)
VALUES
('Ada', 'Lovelace'),
('Grace', 'Hopper'),
('Alan', 'Turing');
CREATE INDEX people_full_name_idx
ON people (full_name);The index stores the generated full_name values along with references to their table rows. PostgreSQL updates both the generated value and the index entry when first_name or last_name changes.
A query can now use the generated column directly:
SELECT id, first_name, last_name
FROM people
WHERE full_name = 'Ada Lovelace';The index is most useful when the condition selects a small part of a large table. PostgreSQL's planner chooses between an index scan and a sequential scan based on table size, statistics, and estimated cost. A small table may use a sequential scan even when an index exists.
Why index the generated column?
The index lets a query search the derived result without repeating its expression:
ANALYZE people;
EXPLAIN (COSTS OFF)
SELECT id
FROM people
WHERE full_name = 'Ada Lovelace';The exact plan depends on the data. On a sufficiently large table, the plan may include an index scan using people_full_name_idx.
An index on full_name supports predicates that use full_name in a compatible way:
| Query condition | Benefit from the index |
|---|---|
| `full_name = 'Ada Lovelace'` | Direct lookup |
| `full_name > 'M'` | Range lookup |
| `ORDER BY full_name` | May avoid a separate sort |
| `lower(full_name) = 'ada lovelace'` | Usually needs a different expression or index |
The last example is important. PostgreSQL cannot generally use an ordinary index on full_name to satisfy a query that applies lower() to the indexed value. If case-insensitive search is required, define the generated column in the desired normalized form or create an expression index:
CREATE INDEX people_lower_full_name_idx
ON people (lower(full_name));
SELECT id
FROM people
WHERE lower(full_name) = 'ada lovelace';The expression used by an index must be immutable. That means the same input must always produce the same output. PostgreSQL needs this property because an index stores results and cannot safely maintain values that change because of the current time, session settings, or outside data.
How the data flows
Indexing trade-offs
The index adds storage and write work. Every insert that creates a generated value must also create an index entry. Every update that changes the generated value may need to remove one index entry and add another.
The index does not make every query faster. It helps when the query's condition matches the indexed column and avoids many rows. A query that returns most of the table may be faster with a sequential scan.
If the generated value is rarely searched, storing and indexing it may cost more than it saves. If the value is searched frequently and the expression is expensive or repeated across many queries, a stored generated column with an index can make the design clearer and the queries simpler.
Exercise
A table has a stored generated column named total defined as quantity * unit_price. What index and query would support finding rows where the total is exactly 500?
Show answer
Create CREATE INDEX orders_total_idx ON orders (total);, then query with WHERE total = 500. PostgreSQL can use the index when its cost estimate favors an index scan.