Sub topic 7
Choosing between stored and virtual
This chapter assumes you can define a generated column, you know that a stored generated column is computed when the row is written, and you know what an index is. It compares the two kinds on storage, write cost, read cost, freshness and restrictions. It ends with a decision procedure you can apply to a real table.
The core difference: when the work happens
A stored generated column is computed on write. PostgreSQL evaluates the expression during INSERT, and during UPDATE when the columns it depends on change. It then saves the result in the row on disk. Reading the column is the same as reading any other column.
A virtual generated column is computed on read. PostgreSQL saves nothing. When a query mentions the column, the query rewriter replaces the reference with the expression, so the expression runs for every row the query touches. Virtual columns need PostgreSQL 18 or later.
Every trade-off below follows from this one difference.
Side by side in one table
You can declare both kinds in the same table to see them behave identically from the outside.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
quantity integer NOT NULL,
unit_price numeric(10,2) NOT NULL,
total_stored numeric(12,2) GENERATED ALWAYS AS (quantity * unit_price) STORED,
total_virtual numeric(12,2) GENERATED ALWAYS AS (quantity * unit_price) VIRTUAL
);
INSERT INTO orders (quantity, unit_price) VALUES (3, 19.99);
SELECT quantity, unit_price, total_stored, total_virtual FROM orders;Both total columns return 59.97. Neither accepts a direct write other than DEFAULT. The differences appear in storage, speed and what you can do with the column.
Storage cost
A stored column makes every row wider. A numeric result adds a few bytes per row, and a long text result, such as a concatenated name or a formatted address, can add a lot. Wider rows mean fewer rows per 8 kB page, a larger table, more I/O for sequential scans, and more memory pressure on the buffer cache.
A virtual column adds nothing to the row. You can measure this by loading the same data into two tables that differ only in the kind of column.
CREATE TABLE sized_stored (
a integer NOT NULL,
b integer NOT NULL,
label text GENERATED ALWAYS AS ('item-' || a::text || '-' || b::text) STORED
);
CREATE TABLE sized_virtual (
a integer NOT NULL,
b integer NOT NULL,
label text GENERATED ALWAYS AS ('item-' || a::text || '-' || b::text) VIRTUAL
);
INSERT INTO sized_stored (a, b)
SELECT g, g % 100 FROM generate_series(1, 200000) AS g;
INSERT INTO sized_virtual (a, b)
SELECT g, g % 100 FROM generate_series(1, 200000) AS g;
SELECT pg_size_pretty(pg_relation_size('sized_stored')) AS stored_size,
pg_size_pretty(pg_relation_size('sized_virtual')) AS virtual_size;stored_size will be noticeably larger than virtual_size. The exact numbers depend on your platform, so run it yourself instead of relying on a figure from a book.
Write cost and read cost
The costs move in opposite directions.
| Aspect | Stored | Virtual |
|---|---|---|
| Evaluated | On `INSERT`, and on `UPDATE` when dependencies change | On every read that references the column |
| Extra disk space | Yes, per row | None |
| Write overhead | Expression cost plus a wider row | None beyond the base columns |
| Read overhead | None for the value itself | Expression cost per row read |
| Bulk load speed | Slower for expensive expressions | Unaffected by the expression |
| Large scans that filter on the column | Reads saved values, but scans a wider table | Evaluates the expression for every row examined |
A cheap expression, such as width * height, costs almost nothing either way, so storage and restrictions decide the choice. An expensive expression, such as a long string build or a heavy numeric calculation, shifts the balance. Where the data is read far more often than it is written, pay the cost once on write and use STORED. Where the data is written often and rarely read through that column, use VIRTUAL.
Row counts matter as well. A virtual column in a SELECT list over ten rows costs ten evaluations. In a WHERE clause over ten million rows with no usable index, it costs ten million evaluations on every execution of the query.
Freshness when an expression's behavior changes
Both kinds are always consistent with the base columns of the same row, so ordinary updates never leave them stale. They differ when something outside the row changes the meaning of the expression.
A stored value is a snapshot. If you change the definition of a user-defined function that the expression calls, the saved values keep the old results until the rows are rewritten. PostgreSQL trusts the function's IMMUTABLE label and does not recompute anything. A virtual column has no snapshot, so every read uses the current function definition.
If you change the expression itself with ALTER TABLE ... ALTER COLUMN ... SET EXPRESSION AS (...), available since PostgreSQL 17, a stored column forces a rewrite of the table to recompute every row. A virtual column has nothing to recompute, so the change is cheap. Adding a new stored generated column to a large table also rewrites it, while adding a virtual one does not.
Restrictions that often decide the choice
Virtual columns trade capability for being free in storage. The main restrictions in PostgreSQL 18 are:
- No index. You cannot create an index on a virtual generated column, or an index that includes one.
- No key constraints. A virtual column cannot take part in a primary key, a unique constraint or a foreign key.
- Built-in only. A virtual column's expression can call only built-in functions and use only built-in types. Stored expressions can call your own immutable functions.
- Replication. Virtual columns are not replicated by logical replication. Stored columns are not published by default either, and PostgreSQL 18 adds a
publish_generated_columnssetting that lets a publication include them.
The next chapters cover indexing and replication in more detail. For now, the practical rule is this. If you need to index the value, use STORED, or index the expression instead. If your expression needs a custom function, use STORED.
The index restriction has a workaround. An ordinary expression index on the same base-column expression does not depend on the virtual column existing. Because the planner replaces the virtual column with its expression, a query can sometimes match that index.
CREATE TABLE rectangles (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
width integer NOT NULL,
height integer NOT NULL,
area integer GENERATED ALWAYS AS (width * height) VIRTUAL
);
-- Fails: PostgreSQL does not support indexes on virtual generated columns.
-- CREATE INDEX rectangles_area_idx ON rectangles (area);
-- Works: an expression index on the base columns.
CREATE INDEX rectangles_area_expr_idx ON rectangles ((width * height));
EXPLAIN SELECT id FROM rectangles WHERE area = 100;Check the plan with EXPLAIN on your own data, because the planner may still choose a sequential scan on a small table. If the index appears in the plan, you get a virtual column for convenient querying and an index for speed. You do pay storage for the index, and the index entries are maintained on every write, so some write cost comes back.
The default changed in PostgreSQL 18
In PostgreSQL 18, writing GENERATED ALWAYS AS (expression) with neither STORED nor VIRTUAL creates a virtual column. In PostgreSQL 12 through 17 the keyword STORED is required, and omitting it is a syntax error.
If you must support servers older than 18, STORED is your only option, and the choice is made for you.
A decision procedure
Work through these questions in order and stop at the first one that gives an answer.
If none of the questions forces STORED, prefer VIRTUAL. It costs no space, it never slows writes, and changing it later is cheap. Choose STORED when you have a concrete reason, such as an index, a key, a custom function or measured read cost.
A few typical cases:
full_namefrom first and last name, searched withWHERE full_name = .... UseSTOREDand index it.areafrom width and height, only displayed in reports. UseVIRTUAL.- A normalized search key, such as
lower(email), used for lookups and uniqueness. UseSTOREDso it can carry an index or a unique constraint. - A
totalfrom quantity and price on a table with heavy insert traffic and occasional reads. UseVIRTUALto keep inserts fast and rows small.
Verifying your choice
Do not guess when the table is large. Load a realistic row count, run your real queries, and compare plans and timings.
EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM sized_stored WHERE label = 'item-1000-0';
EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM sized_virtual WHERE label = 'item-1000-0';The sized_stored and sized_virtual tables here do not have an id column, so select a instead if you reuse the tables from the size example. Compare the Buffers counts and the execution time. The stored table reads more pages because its rows are wider, but it compares saved text. The virtual table reads fewer pages but builds the string for each row. Which one wins depends on your hardware and data, which is why the measurement matters.
Exercise
A table named readings is written about 5,000 times per second and queried a few times per hour. Each row has two integer columns, and you want a derived column equal to their sum. You never filter or join on the derived value. The server runs PostgreSQL 18. Which kind of generated column do you choose, and what would change your answer?
Show answer
Choose VIRTUAL. The expression is cheap, so evaluating it on the rare reads costs little, and a virtual column adds no bytes to each row and no work to the heavy write path. Your answer would change to STORED if you needed to index the value or put a unique or foreign key on it, if the expression used a custom function or type, if you measured that read-time evaluation was too slow, or if the server were older than PostgreSQL 18, where VIRTUAL does not exist.
Exercise
You run CREATE TABLE t (a integer, b integer GENERATED ALWAYS AS (a * 2)); with no STORED or VIRTUAL keyword. What happens on PostgreSQL 17 and on PostgreSQL 18?
Show answer
On PostgreSQL 17 the statement fails with a syntax error, because STORED is required before version 18. On PostgreSQL 18 it succeeds and creates a virtual generated column, because VIRTUAL is the default. This is why migrations should always name the kind explicitly.