Sub topic 6
Virtual generated columns
This chapter assumes you know how stored generated columns work: GENERATED ALWAYS AS (expression) STORED, the immutability rule for the expression, and the fact that you cannot write to a generated column directly. You should also know what a view is and what an expression index does. Virtual generated columns are a PostgreSQL 18 feature. If your server is older, you can read this chapter, but the examples will not run.
What "virtual" means
A virtual generated column is declared like a stored one, but the keyword is VIRTUAL. PostgreSQL keeps no value for it on disk. Each time a query reads the column, the server evaluates the expression from the other columns of the same row.
CREATE TABLE rectangles (
width integer NOT NULL,
height integer NOT NULL,
area integer GENERATED ALWAYS AS (width * height) VIRTUAL
);
INSERT INTO rectangles (width, height) VALUES (3, 4), (10, 20);
SELECT width, height, area FROM rectangles; width | height | area
-------+--------+------
3 | 4 | 12
10 | 20 | 200The result looks the same as it would with STORED. The difference is below the surface. The heap tuple (the row as saved in the table file) holds only width and height.
In PostgreSQL 18, VIRTUAL is the default. If you write GENERATED ALWAYS AS (expr) with neither keyword, you get a virtual column. Older versions require the word STORED. In a schema that must run on several versions, write the keyword every time.
How the server evaluates it
When PostgreSQL parses a query that mentions area, the rewriter replaces the column reference with the generation expression. This is the same mechanism that expands a view into its defining query. So this query:
SELECT id_like_filter FROM (SELECT 1) AS s, rectangles WHERE area > 100;is planned as if you had written WHERE width * height > 100. The planner never sees a column called area, only the expression. Three consequences follow:
- Reading a row never needs more I/O because of the column, but it costs CPU for every row where the column is used.
- Statistics, costing and plan choice work on the expanded expression.
- An expression index on the same expression can be used. For example, an index on
((width * height))matchesWHERE area > 100after rewriting. You cannot index the virtual column itself (see the limits below), but this route gives you indexed lookups.
CREATE INDEX rectangles_area_expr_idx ON rectangles ((width * height));
EXPLAIN SELECT * FROM rectangles WHERE area = 200;On a table large enough for the planner to prefer an index, the plan shows the filter as (width * height) = 200. That confirms the rewrite. On a tiny table you will see a sequential scan, because it is cheaper.
Write behavior
From the user's side, writes behave the same as for stored columns:
- You cannot insert or update a non-
DEFAULTvalue. An attempt fails withcannot insert a non-DEFAULT value into column "area". INSERT INTO rectangles (width, height, area) VALUES (1, 2, DEFAULT)is allowed.- When
widthorheightchanges, the next read ofareareturns the new result. No recomputation happens at update time, because nothing is stored.
This is where the cost model differs. A stored column costs the expression evaluation on every write of the row and extra bytes in every row. A virtual column costs nothing on write and nothing in table size, and it pays on each read.
Errors move from write time to read time
This is the most surprising consequence. A stored column evaluates its expression during INSERT or UPDATE, so an error such as an overflow is raised by the statement that wrote the bad data. A virtual column does not evaluate during the write, so the same bad row can be written successfully and fail later, in someone else's query.
INSERT INTO rectangles (width, height) VALUES (100000, 100000);
-- INSERT 0 1: succeeds, the product is never computed
SELECT area FROM rectangles;
-- ERROR: integer out of rangeThe failing query is any query that reads area for that row, even one that filters on a different column, because the expression is evaluated when the column is used in a select list or a condition. A query that does not mention area (for example SELECT width FROM rectangles) still works.
Two ways to defend against this:
- Use a wider type in the expression, for example
(width::bigint * height)with abigintcolumn. - Add a
CHECKconstraint on the column. Check constraints on a virtual column are evaluated when a row is written, so they reject bad rows at write time.
DELETE FROM rectangles WHERE width = 100000;
ALTER TABLE rectangles
ADD CONSTRAINT rectangles_area_positive CHECK (area > 0);The constraint forces the expression to be evaluated on writes, which restores the write-time error behavior at the cost of the CPU you were trying to avoid. Use it where the data quality matters more than the write speed.
Rules the expression must follow
Everything that applies to stored generated columns applies here: the expression must be immutable, must reference only columns of the same row, and cannot contain a subquery. A generated column cannot reference another generated column.
Virtual columns have extra restrictions in PostgreSQL 18:
- The expression cannot call user-defined functions, and it cannot use user-defined types. Built-in functions and operators on built-in types are fine.
- The column itself cannot have a user-defined type.
The reason is the expansion described above. The expression is pasted into any query that reads the column, and that query can run as a different role, with a different search_path. Restricting the expression to built-in objects prevents a definition from being changed later (or resolved differently) in a way that would affect other users' queries. A stored column does not have this problem, because its expression runs only at write time, under the writer's own privileges.
The immutability rule also still applies. The to_char(ts, 'YYYY') example from the earlier chapter, which depends on the session time zone, is rejected for VIRTUAL in the same way as for STORED.
What a virtual column cannot do
Because there is no stored value, anything that needs a physical value is unavailable. In PostgreSQL 18 these are not supported on a virtual generated column:
| Feature | Virtual column | Workaround |
|---|---|---|
| Index on the column | Not allowed | Index the expression directly, or use a stored column |
| `UNIQUE` or `PRIMARY KEY` on the column | Not allowed, because both need an index | Unique index on the expression |
| Use as a foreign key column | Not allowed | Use a stored column |
| Partition key | Not allowed | Use a stored column or partition by the base columns |
| Logical replication of its values | Not sent to subscribers | Compute the same expression on the subscriber, or use a stored column |
CHECK constraints are allowed, as shown above. Treat the table as the authority for the current list of limits, and check the release notes of the minor version you run, because restrictions in a first release of a feature tend to be lifted over time.
Adding and changing virtual columns
Adding a virtual column to an existing table is a catalog-only change:
ALTER TABLE rectangles
ADD COLUMN perimeter integer
GENERATED ALWAYS AS (2 * (width + height)) VIRTUAL;PostgreSQL does not rewrite the table and does not scan it, because no value needs to be created. Adding a stored column, by contrast, rewrites the whole table, so it holds a long lock on a large table. If you are unsure whether you will ever need an index, a virtual column is the cheaper first step.
To change the formula, ALTER COLUMN ... SET EXPRESSION AS (...) replaces it. For a virtual column this is also a catalog-only change, so the new formula applies to every row at once. For a stored column the same command rewrites the table.
ALTER TABLE rectangles
ALTER COLUMN perimeter SET EXPRESSION AS (2 * (width::bigint + height));That statement would change the type used inside the expression only. If the result type of the column must change as well, use ALTER COLUMN ... TYPE first or in the same command.
Stored or virtual: a decision guide
The two kinds trade write cost, read cost and storage against each other.
| Aspect | Stored | Virtual (PostgreSQL 18+) |
|---|---|---|
| Disk space | Extra bytes in each row | None |
| `INSERT` and `UPDATE` cost | Evaluates expression on each write | No evaluation, unless a `CHECK` uses it |
| `SELECT` cost | Reads a saved value | Evaluates per row, per query |
| Direct index, unique, foreign key | Yes | No |
| Add column to a large table | Table rewrite | Catalog change only |
| Changing the expression | Table rewrite | Catalog change only |
| Allowed expression | Any immutable expression | Immutable, built-in functions and types only |
| Replicated logically | Possible, depending on publication settings | No |
Choose virtual when:
- the expression is cheap (arithmetic, concatenation,
lower()), - the table is write-heavy or wide and you want to keep rows small,
- the column is read rarely or in few queries,
- you do not need to index, constrain or replicate the column directly.
Choose stored when:
- the expression is expensive and the column is read often,
- you need an index, a unique constraint or a foreign key on the value,
- you need the value in logical replication,
- you want write-time errors without adding a
CHECK.
A common pattern is to start with a virtual column, watch the queries that use it, and move to a stored column only if profiling shows that repeated evaluation matters. Moving means dropping the virtual column and adding a stored column with the same name. That is a table rewrite, and it should be done in a maintenance window or with a new column name followed by a rename.
Common mistakes
- Using
VIRTUALon PostgreSQL 17 or earlier. The statement fails with a syntax error, because onlySTOREDis accepted there. - Relying on the default keyword. On version 18 it creates a virtual column, and the same script creates a stored column on older versions only if
STOREDis written explicitly. - Expecting
CREATE INDEX ON t (virtual_col)to work. It fails. Index the expression instead. - Calling your own immutable function in the expression. It works for stored columns and is rejected for virtual ones.
- Assuming that a successful
INSERTmeans the derived value is valid. For a virtual column it only means the base columns were accepted.
Exercise
A table has price numeric NOT NULL, qty integer NOT NULL, and total numeric GENERATED ALWAYS AS (price * qty) VIRTUAL. A dashboard runs SELECT * FROM orders WHERE total > 1000 many times per minute on a table with 50 million rows, and it is slow. You cannot run CREATE INDEX ON orders (total). Why not, and what are two ways to make the query use an index?
Show answer
The total column is virtual, so no value is stored and PostgreSQL 18 does not allow an index on a virtual generated column. Option 1: create an expression index on the same expression, CREATE INDEX ON orders ((price * qty)). The planner expands total into price * qty, so the index matches the condition. Option 2: replace the virtual column with a stored one (GENERATED ALWAYS AS (price * qty) STORED) and index it with a normal CREATE INDEX ON orders (total). Option 2 rewrites the table and uses extra storage. Option 1 keeps the column virtual and needs no rewrite of the table, only an index build.
Exercise
Table t has a integer and b integer GENERATED ALWAYS AS (a * 1000000) VIRTUAL. A developer runs INSERT INTO t (a) VALUES (5000), which reports success. Later SELECT b FROM t fails. What happened, and what would have happened with STORED?
Show answer
The product 5,000,000,000 exceeds the integer range. With VIRTUAL, the expression is not evaluated during INSERT, so the insert succeeds and the error appears when a query reads b for that row. With STORED, the expression is evaluated during the INSERT, so the insert itself would fail with integer out of range and the row would never be written. A CHECK constraint on b, or a bigint cast in the expression, would prevent the late failure.
Exercise
You must add a derived column label (lower(name)) to a 2 TB table without a long lock, and you do not need to index it. Which kind do you choose and why?
Show answer
Choose VIRTUAL. Adding a virtual column changes only the catalog, with no table rewrite, so the ALTER TABLE finishes quickly and the lock is short. Adding a stored column rewrites all 2 TB. The lower() function is built in and immutable, so it is allowed in a virtual expression.