Resources / PostgreSQL Tutorial

Generated Columns

Generated Columns explained with practical SQL patterns, edge cases, and production-ready guidance.

10 min read

Spin up a Postgres database in 20 seconds with Vela.

Try Vela Sandbox

Generated Columns in Managing Tables helps you write SQL that is easier to test, review, and operate at scale.

Introduction to Generated Columns

Use Generated Columns to evolve schema safely as your application grows.

Commonly paired with: FROM, WHERE, EXCEPT, WITH.

Practical examples with Generated Columns in PostgreSQL

Reference pattern: start from canonical syntax and keep it explicit.

CREATE TABLE line_items (
  qty INTEGER NOT NULL,
  unit_price NUMERIC(10,2) NOT NULL,
  total_price NUMERIC(10,2) GENERATED ALWAYS AS (qty * unit_price) STORED
);

Production-style scenario: apply the same concept to realistic application data.

BEGIN;
ALTER TABLE orders ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT now();
CREATE INDEX IF NOT EXISTS idx_orders_updated_at ON orders (updated_at DESC);
COMMIT;

Additional example: use a variation to validate behavior and edge cases.

ALTER TABLE orders
ADD CONSTRAINT orders_total_nonnegative CHECK (total_amount >= 0);

Production tips

  • Prefer explicit column lists and deterministic ordering when results feed APIs or batch jobs.
  • Validate plans with EXPLAIN before adding indexes, then re-check after schema changes.
  • Keep DDL, data backfills, and cleanups in transactions when possible to avoid partial state.
  • Use isolated environments for risky changes so query tuning and schema experiments stay safe.

Vela workflow tip

Test this pattern in an isolated branch database, share the result with your team, and promote only after query plans and row counts look correct.

Reference: PostgreSQL official documentation.

Continue through the next items in Managing Tables: Alter Table .

Related: PostgreSQL Data Types Create Table Select Into