Nov 23, 20265 min read

Postgres Generated Columns: When to Use Them in an API

What GENERATED ALWAYS AS ... STORED does, the jobs it handles well (totals, search vectors, JSON fields you filter on), the immutability rule, the table rewrite when you add one, and a Go example on Encore.

Illustration for Postgres Generated Columns: When to Use Them in an API

Some values in a row are functions of other values in the same row: an order total, a lowercased email, a search vector. Computing them in application code works until a second code path writes the row and forgets.

Generated columns move that computation into the schema, where Postgres keeps it correct on every write. This guide covers where they help, the rules that trip people up and how they fit a Go API.

What does a generated column do?

You declare the column with an expression, and Postgres fills it in on every insert and update:

total_cents BIGINT GENERATED ALWAYS AS (unit_price_cents::bigint * quantity) STORED

Applications cannot write to it, and trying returns "cannot insert a non-DEFAULT value into column", so there is exactly one definition of the value and it lives in the table. The Postgres documentation on generated columns describes two kinds. Stored columns are computed on write and saved, so they can be indexed. Virtual columns, introduced in Postgres 18 and the default there, are computed on read and take no space.

What are generated columns good for?

Derived values that must never drift. Totals, durations and normalized forms of input, where a mismatch between the stored value and its inputs would be a bug.

Search columns. A tsvector built with to_tsvector('english', title || ' ' || description) and a GIN index gives you full-text search without a trigger to maintain the vector.

Fields pulled out of JSON. When you filter on one key of a JSONB payload all the time, customer_ref TEXT GENERATED ALWAYS AS (payload->>'customer_ref') STORED plus a B-tree index is simpler to query and to read in EXPLAIN output than an expression index on the JSON path.

What are the limits?

The expression must be immutable. now(), random() and anything that reads another table are rejected, and so is to_tsvector(title) without an explicit configuration, since its result depends on the default_text_search_config setting. We hit both errors on Postgres 17: adding now()::date and the one-argument to_tsvector each failed with "generation expression is not immutable", while to_tsvector('english', title) worked.

A generated column cannot reference another generated column, cannot be part of a partition key, and cannot have a default. Values that depend on time or on other rows, such as "days overdue" or "number of items in the order", belong in a view, a query or a trigger instead.

What does adding one to an existing table cost?

Adding a stored generated column computes the value for every existing row, which rewrites the table under an ACCESS EXCLUSIVE lock, as the ALTER TABLE documentation notes for column additions that need new values. On a small table that is a blink. On a table with tens of millions of rows it blocks reads and writes for the duration, so plan it like any other heavy migration, or on Postgres 18 add a virtual column, which needs no rewrite.

Generated columns with Encore

Encore

Encore is a backend framework with built-in infrastructure, and the schema with its generated columns sits in migration files inside the same Go service as the endpoints that read them. The Postgres database applies those migrations locally under encore run and in every deployed environment, and the schema change workflow is plain numbered SQL files, so generated columns need no ORM support.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

-- orders/migrations/1_create_orders.up.sql CREATE TABLE orders ( id BIGSERIAL PRIMARY KEY, title TEXT NOT NULL, unit_price_cents INT NOT NULL, quantity INT NOT NULL CHECK (quantity > 0), payload JSONB NOT NULL DEFAULT '{}', total_cents BIGINT GENERATED ALWAYS AS (unit_price_cents::bigint * quantity) STORED, customer_ref TEXT GENERATED ALWAYS AS (payload->>'customer_ref') STORED, search TSVECTOR GENERATED ALWAYS AS (to_tsvector('english', title)) STORED ); CREATE INDEX orders_customer_ref ON orders (customer_ref); CREATE INDEX orders_search ON orders USING gin (search);
// orders/orders.go package orders import ( "context" "encoding/json" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("orders", sqldb.DatabaseConfig{Migrations: "./migrations"}) type CreateParams struct { Title string UnitPriceCents int32 Quantity int32 Payload json.RawMessage } type Order struct { ID int64 Title string TotalCents int64 CustomerRef *string } //encore:api private method=POST path=/orders func Create(ctx context.Context, p *CreateParams) (*Order, error) { payload := p.Payload if len(payload) == 0 { payload = json.RawMessage("{}") } o := &Order{Title: p.Title} // total_cents, customer_ref and search are filled in by Postgres. err := db.QueryRow(ctx, ` INSERT INTO orders (title, unit_price_cents, quantity, payload) VALUES ($1, $2, $3, $4::jsonb) RETURNING id, total_cents, customer_ref`, p.Title, p.UnitPriceCents, p.Quantity, string(payload), ).Scan(&o.ID, &o.TotalCents, &o.CustomerRef) if err != nil { return nil, err } return o, nil } type SearchParams struct { Q string `query:"q"` CustomerRef string `query:"customer_ref"` } type SearchResponse struct { Orders []*Order } //encore:api private method=GET path=/orders/search func Search(ctx context.Context, p *SearchParams) (*SearchResponse, error) { rows, err := db.Query(ctx, ` SELECT id, title, total_cents, customer_ref FROM orders WHERE ($1 = '' OR search @@ websearch_to_tsquery('english', $1)) AND ($2 = '' OR customer_ref = $2) ORDER BY id DESC LIMIT 50`, p.Q, p.CustomerRef) if err != nil { return nil, err } defer rows.Close() resp := &SearchResponse{} for rows.Next() { o := &Order{} if err := rows.Scan(&o.ID, &o.Title, &o.TotalCents, &o.CustomerRef); err != nil { return nil, err } resp.Orders = append(resp.Orders, o) } return resp, rows.Err() }

RETURNING hands back the computed values from the same statement, so the API responds with the total Postgres calculated rather than one recomputed in Go. encore run starts Postgres locally and applies the migration, which is also where an expression that is not immutable fails, long before it reaches a deployed environment, and each query shows up in the local trace.

Agents tend to add a computed field by calculating it in the handler. With the rule in the schema, a new endpoint that writes orders gets the correct total without anyone remembering to copy the formula, and the local migration run catches an invalid expression in the same session.

Best fit: Services that want totals, search vectors and extracted JSON fields kept correct by the Postgres database they run in their own cloud account.

Frequently asked questions

What is a generated column in Postgres?

A column whose value Postgres computes from other columns in the same row using an expression you declare, such as total_cents GENERATED ALWAYS AS (unit_price_cents * quantity) STORED. The value updates whenever the row changes, and applications cannot write to it.

What is the difference between stored and virtual generated columns?

A stored generated column is computed on write and saved on disk, so it can be indexed and costs nothing to read. A virtual one, added in Postgres 18 and its default kind, is computed when the row is read and takes no storage.

Why does Postgres say the generation expression is not immutable?

Generated column expressions may only use immutable functions, whose result depends on nothing but their arguments. now() and to_tsvector without an explicit configuration fail the check; to_tsvector('english', title) passes because the configuration is fixed.

How do I use generated columns with Encore?

Declare them in a migration for an Encore Postgres database and leave them out of INSERT and UPDATE statements in your endpoints, then read and index them like any other column. encore run starts Postgres locally and applies the migration.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders