Video in progress

What is a generated column (`GENERATED ALWAYS AS (...) STORED`) and when is it useful?

It's a column whose value is computed automatically from other columns and stored on disk. You can't write to it by hand, so even if the application forgets, the value is always right. It's handy when you need to filter and index by a computed value.

📖 Answer

For example, a tsvector for full-text search on a product name, or a field from a jsonb that you need often.

ALTER TABLE events
  ADD COLUMN event_type text
  GENERATED ALWAYS AS (payload ->> 'type') STORED;

CREATE INDEX ON events (event_type);

Now WHERE event_type = 'LOGIN' uses a regular index and shows up as an ordinary column in the ORM.

Limitations:

  • the expression can use only columns of the same row and immutable functions: you can't use now() or refer to another table;
  • adding it to an existing big table rewrites the whole table and holds an ACCESS EXCLUSIVE lock the whole time;
  • in PostgreSQL 12-17 only STORED exists; PG18 added virtual (not stored) generated columns too, and made them the default.

In JPA I mark such a column @Column(insertable = false, updatable = false), otherwise Hibernate tries to write a value into it and the database raises an error.

In many cases an expression index (CREATE INDEX ON events ((payload->>'type'))) does the same job. I choose a generated column when the value also has to be shown often in SELECT.