Sub topic 12
When to use something else
A generated column covers a narrow case well: a value computed from other columns of the same row, kept correct by the database. This chapter covers the cases it does not fit. Views, expression indexes, and triggers each cover part of that gap, and some needs are better met by a plain DEFAULT or a materialized view.
This chapter assumes you know basic SQL, the difference between a table and a view, and what an index does. It also assumes you have read the earlier chapters on stored and virtual generated columns, including the immutability rule and the PostgreSQL 18 requirement for VIRTUAL.
What a generated column cannot do
Before picking an alternative, check which requirement the generated column fails. The common ones are:
- The value needs other rows or tables. A generation expression sees only the current row. It cannot contain a subquery or an aggregate.
- The expression is not immutable. Functions such as
now()orrandom(), and anything that depends on a session setting such as the time zone, are rejected when the table is created. - The value must be writable. A generated column accepts only
DEFAULTon insert and update. If the application needs to override the value sometimes, it cannot be generated. - You want an index but not the extra column. A stored generated column duplicates data in the table. If the value is only needed to find rows, an index alone may be enough.
- You need a virtual column on a version before 18. Only PostgreSQL 18 and later support
VIRTUAL.
Each alternative below answers one or more of these.
Expression indexes
An expression index is an index built on the result of an expression rather than on a column. It stores computed values in the index only. The table gets no extra column.
CREATE TABLE accounts (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL
);
CREATE UNIQUE INDEX accounts_email_lower_idx ON accounts (lower(email));
SELECT id FROM accounts WHERE lower(email) = '[email protected]';The unique index also enforces case-insensitive uniqueness. [email protected] and [email protected] cannot both exist.
The comparison with a stored generated column plus an index:
| Aspect | Expression index | Stored generated column + index |
|---|---|---|
| Extra data in the table | None | One value per row |
| Extra data in the index | One entry per row | One entry per row |
| Can be selected as a column | No, repeat the expression | Yes, by name |
| Query must repeat the expression | Yes, exactly | No, use the column name |
| Visible in `SELECT *` | No | Yes |
| Expression rules | Immutable functions only | Immutable functions only |
The expression rule is the same in both cases, so an expression index does not get you around immutability. Both reject the to_char(timestamptz, ...) example from earlier.
The main failure mode is a query that does not match the indexed expression. An index on lower(email) does not help WHERE email ILIKE 'ada%' or WHERE lower(trim(email)) = .... If many queries and many developers touch the value, a named column is harder to get wrong. If only one or two queries need the lookup, the expression index avoids storing the value twice.
In PostgreSQL 18 you cannot index a virtual generated column directly. An expression index over the same expression gives you the same lookup speed, with the column still available for reading.
Views
A view stores a query, not data. It can compute anything a SELECT can compute, including joins, aggregates, and subqueries. This makes it the right tool when the derived value depends on more than one row.
CREATE TABLE orders (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id integer NOT NULL
);
CREATE TABLE order_lines (
order_id integer NOT NULL REFERENCES orders (id),
quantity integer NOT NULL,
unit_price numeric(10, 2) NOT NULL
);
CREATE VIEW order_totals AS
SELECT o.id AS order_id,
sum(l.quantity * l.unit_price) AS total
FROM orders o
JOIN order_lines l ON l.order_id = o.id
GROUP BY o.id;
SELECT total FROM order_totals WHERE order_id = 1;A generated column on orders cannot hold this total, because the line items live in another table.
A view can also stand in for a virtual column on versions before 18:
CREATE VIEW people_with_name AS
SELECT p.*, p.first_name || ' ' || p.last_name AS full_name
FROM people AS p;This works on every supported version. It has three costs:
- The computed value lives in a separate object, so applications must read from the view and write to the table.
p.*is expanded when the view is created. Columns added topeoplelater do not appear in the view until you recreate it.- Planning a query on a view takes slightly more work than reading a column, though simple views are inlined into the query.
Views do not store anything, so they do not slow down writes. Their cost is paid at read time, as with a virtual column.
Materialized views
If the view's query is expensive and the data can be slightly old, a materialized view stores the result on disk. You refresh it on demand with REFRESH MATERIALIZED VIEW, and you can index it. It does not update itself when the base tables change. That makes it a poor substitute for a generated column, which is always current. It is the better choice for reports and dashboards that tolerate a delay.
Triggers
A BEFORE INSERT OR UPDATE trigger can change the row before it is written. This gives you a computed value with none of the generated-column restrictions. The trigger function can call now(), read other tables, or call any function whatever its volatility.
CREATE TABLE documents (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
body text NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE FUNCTION set_updated_at() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW;
END;
$$;
CREATE TRIGGER documents_set_updated_at
BEFORE UPDATE ON documents
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
INSERT INTO documents (body) VALUES ('first draft');
UPDATE documents SET body = 'second draft' WHERE id = 1;
SELECT updated_at FROM documents WHERE id = 1;A generated column cannot do this, because now() is not immutable.
The trade-offs are real:
- More code to maintain. You own the function, the trigger, and any tests for them.
- Weaker guarantees. The column is an ordinary writable column. Without extra checks, a client can set
updated_atto anything. ABEFOREtrigger overrides what the client sent only if it assigns the column unconditionally, as the example does. Settingsession_replication_roletoreplicaalso stops ordinary triggers from firing, which bulk-load and replication tools sometimes use. - Easy to get wrong. If the trigger does not cover every operation that changes the dependent inputs, the stored value goes stale. A generated column cannot go stale this way.
- Per-row overhead. Row-level triggers run procedural code for each row, which is slower than a built-in expression.
Use a trigger when the requirement is outside what the database can express declaratively. Do not use one for a value like full_name, where a generated column is simpler and cannot drift.
Defaults for one-time values
Some values are computed once at insert and never again. A DEFAULT expression fits these. Defaults may use volatile functions, and the value stays writable afterwards.
CREATE TABLE sessions (
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
created_at timestamptz NOT NULL DEFAULT now()
);gen_random_uuid() is built in from PostgreSQL 13. A generated column would be wrong here for two reasons. Neither function is immutable, and you do not want the value to recompute when the row changes.
Choosing between the options
The decision depends on four questions. Does the value depend on one row? Is the expression immutable? Must the database guarantee it is current? Must it be indexed?
A summary by need:
| Need | Best fit | Why |
|---|---|---|
| Value from the same row, must always match its inputs | Generated column | The database enforces it, and clients cannot override it |
| Fast lookup on a function of a column | Expression index | No extra column in the table |
| Value from joins or aggregates | View | A generated column cannot see other rows |
| Expensive result, some staleness is fine | Materialized view | Stored and indexable, refreshed on demand |
| Timestamp set when a row changes | Trigger | Needs `now()`, which is not immutable |
| Value set once at insert | `DEFAULT` | Allows volatile functions, and the value stays as written |
| Computed column on PostgreSQL 17 or earlier, no storage | View | `VIRTUAL` does not exist there |
Combining options is common. A table can have a stored generated column for a search key, an expression index for a different lookup, and a view that joins to other tables for reporting.
Common mistakes
- Using a trigger for a same-row immutable calculation. The generated column is shorter and cannot go stale.
- Writing a query that does not match the index expression. Check with
EXPLAINthat the planner uses the index. - Expecting a view to behave like a column on writes. You cannot insert into a computed expression of a view, and writes through a view must target the base columns.
- Treating a materialized view as always current. It shows the data as of the last refresh.
- Using
DEFAULTwhen the value should follow its inputs. A default is computed once. After an update tofirst_name, a default-basedfull_namestays as it was.
Exercise
A table invoices has a paid_at timestamptz column. You want an is_overdue column that is true when paid_at IS NULL and the invoice's due date has passed, using the current time. Can this be a generated column? Name a better option.
Show answer
No. The expression needs the current time, and now() is not immutable, so PostgreSQL rejects it in a generation expression. A stored value would also go stale as time passes without any row change. Compute it at read time instead, for example in a view with paid_at IS NULL AND due_date < now(), or in the query itself. A trigger would not help, because nothing fires when time simply passes.
Exercise
You have people with first_name and last_name. Reports need full_name in SELECT lists. Searches need to find rows by lowercase full name quickly. Which two features would you combine on PostgreSQL 17, and what changes on PostgreSQL 18?
Show answer
On PostgreSQL 17, use a stored generated column for full_name so reports can select it by name, and an expression index on lower(full_name) for searches. Queries must use lower(full_name) exactly. On PostgreSQL 18, full_name could be VIRTUAL to save storage, since the lookup is served by the expression index. A virtual column cannot be indexed directly, so the index must be an expression index over the same expression.