Trending

World technology news

→
PostgreSQL 18 virtual generated columns: Validating order line totals
Software Engineering · 2025
Software Engineering2025

PostgreSQL 18 virtual generated columns: Validating order line totals

Use a small order-line example to compare virtual and stored generated columns in PostgreSQL 18, then check read cost, write cost, correctness and version compatibility.

Archive retrospective · Topic year 2025

Developer's JournalPublished: Dec 4, 20266 min read
Reading progress0%
In this article
  1. The option introduced in PostgreSQL 18
  2. Define an order line total once
  3. Keep cross-row business rules explicit
  4. Measure reads and writes separately
  5. Check compatibility and expected values before release
  6. Local test: Boundaries and a rejected write

The option introduced in PostgreSQL 18

The PostgreSQL Global Development Group released version 18 on September 25, 2025. That release added virtual generated columns, which are computed when read. VIRTUAL became the default when a generated column declaration leaves the kind unspecified. A STORED column is calculated when its row is written and the result is stored with the row. Spelling out the chosen kind makes its cost easier to see in a migration file. The PostgreSQL 18 documentation linked from the release provides the precise constraints on generation expressions and the two column kinds.

Define an order line total once

Store the unit price at the time of the order in minor currency units and record the quantity on the same row. The example below starts with three units at 1,200, giving a total of 3,600. Updating the quantity to four gives 4,800 in both generated columns. Defining both versions in one temporary table makes it easy to compare their values. Choose a single version in a real schema. Since the report uses the price that was agreed when the order was placed, there is no lookup to the current catalogue price. PostgreSQL 18.7 returned the stated results in a single session. Use the same session for the entire example because the table is temporary.

Database access flowConceptual sketch · summary of the article's technical flow
Illustrative diagram by Yazılımcının Günlüğü
CREATE TEMP TABLE order_line (
  id integer PRIMARY KEY,
  unit_cents bigint NOT NULL CHECK (unit_cents BETWEEN 0 AND 1000000000),
  quantity integer NOT NULL CHECK (quantity BETWEEN 1 AND 100000),
  total_virtual bigint GENERATED ALWAYS AS (unit_cents * quantity) VIRTUAL,
  total_stored bigint GENERATED ALWAYS AS (unit_cents * quantity) STORED
);
INSERT INTO order_line (id, unit_cents, quantity) VALUES (1, 1200, 3);
SELECT total_virtual, total_stored FROM order_line WHERE id = 1;
UPDATE order_line SET quantity = 4 WHERE id = 1
RETURNING total_virtual, total_stored;

Keep cross-row business rules explicit

The PostgreSQL 18 documentation limits a generation expression to immutable operations on the current row. The expression cannot contain a subquery or refer to another generated column. Virtual columns have additional restrictions on user-defined functions and types. If a discount depends on a campaign in another table, store the agreed discount on the order line or join to the campaign explicitly for a report that needs today’s rules. Make the choice visible so that the finance team can reproduce a historical total and identify which input values were used.

Measure reads and writes separately

Create two test tables with the same source data. Give one table a virtual column and the other a stored column. Run the same aggregate query and filter on both tables, recording the query plan and buffer usage. In a separate run, compare order inserts and quantity updates. Examine table size and results across repeated runs. The sample with both generated columns in one table is useful for checking correctness. Separate tables make it easier to attribute a difference in storage or write cost to the column kind you are testing.

Check compatibility and expected values before release

Record SHOW server_version on each deployment target. For a target older than PostgreSQL 18, use a migration that declares STORED explicitly or a view that computes the value if that meets your requirements. Verify zero pricing, the upper quantity limit and a quantity change against known totals. Run the same cases through the query that exports the report. Confirm that analytics roles can read the field and that applications write the base inputs. Save the expected outputs with the migration so a future maintainer can repeat the verification.

Local test: Boundaries and a rejected write

The rerun used PostgreSQL 18.7 on Windows. It returned 3600 in both columns after insertion and 4800 after the quantity update. Two boundary rows produced zero and 100000000000000. An insert with zero quantity raised the expected check violation. The assertions verify those results and compare the two generated columns across all accepted rows. This is an observation on a maintenance release in the 18 series, not a benchmark or a rerun of the first 18.0 release. The schema example provides just one pricing currency and one chosen range for quantity and unit cost. A little more design work is needed after deciding how the amount is computed. An editable order can keep reflecting quantity changes, while an issued invoice may need to retain the agreed amount. A generated value based on current order inputs will change again if the inputs change. Model the point at which the invoice becomes fixed. For example, tests can compare an order edited after checkout with the already issued invoice. They can also verify that a writer submits the base inputs and that an export gets the expected numeric type. Evaluate read and write costs on representative workloads after those semantic checks pass. Where privileges matter, exercise the least-privileged roles actually used by those jobs.

CREATE TEMP TABLE order_line (
  id integer PRIMARY KEY,
  unit_cents bigint NOT NULL CHECK (unit_cents BETWEEN 0 AND 1000000000),
  quantity integer NOT NULL CHECK (quantity BETWEEN 1 AND 100000),
  total_virtual bigint GENERATED ALWAYS AS (unit_cents * quantity) VIRTUAL,
  total_stored bigint GENERATED ALWAYS AS (unit_cents * quantity) STORED
);
INSERT INTO order_line (id, unit_cents, quantity) VALUES (1, 1200, 3);
SELECT total_virtual, total_stored FROM order_line WHERE id = 1;
UPDATE order_line SET quantity = 4 WHERE id = 1
RETURNING total_virtual, total_stored;
INSERT INTO order_line (id, unit_cents, quantity)
VALUES (2, 0, 5), (3, 1000000000, 100000);
SELECT id,total_virtual,total_stored FROM order_line ORDER BY id;
DO $$
BEGIN
  IF (SELECT total_virtual FROM order_line WHERE id=1) IS DISTINCT FROM 4800::bigint OR
     (SELECT total_virtual FROM order_line WHERE id=2) IS DISTINCT FROM 0::bigint OR
     (SELECT total_virtual FROM order_line WHERE id=3) IS DISTINCT FROM 100000000000000::bigint OR
     EXISTS(SELECT 1 FROM order_line WHERE total_virtual IS DISTINCT FROM total_stored) THEN
    RAISE EXCEPTION 'Generated totals differ from fixture';
  END IF;
  BEGIN
    INSERT INTO order_line (id, unit_cents, quantity) VALUES (4, 1200, 0);
    RAISE EXCEPTION 'Zero quantity was accepted';
  EXCEPTION WHEN check_violation THEN
    RAISE NOTICE 'zero quantity rejected';
  END;
END
$$;
181 reads ✎ Write a comment

Reader discussion

Discussion prompt

What would you change first for maintainability and testing in your own project?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.