Temporary tables and generated columns
Overview
A temporary table is a database object with limited lifetime, useful for staging intermediate data across statements. A generated column derives its value from other columns in the same row. The two features solve different problems: lifetime versus calculated values.
First example
CREATE TEMP TABLE stage_ids (id INTEGER);INSERT INTO stage_ids VALUES (1),(2);SELECT COUNT(*) FROM temp.stage_ids;Observed SQLite result (rows in JSON):
[ [ 2 ]]How it works
SQLite temporary tables are connection-local. PostgreSQL temporary tables can also have explicit ON COMMIT behavior. SQLite supports VIRTUAL and STORED generated columns; PostgreSQL 17 supports STORED generated columns. Unlike a default, a generated expression follows changes in its source columns. Do not insert directly into a generated column. This example calculates integer-cent line totals; use appropriate numeric limits in real systems.
Practical example
CREATE TABLE lines (qty INTEGER, price_cents INTEGER, total INTEGER GENERATED ALWAYS AS (qty*price_cents) STORED);INSERT INTO lines(qty,price_cents) VALUES (2,100);UPDATE lines SET qty=3;SELECT qty,price_cents,total FROM lines;Observed SQLite result (rows in JSON):
[ [ 3, 100, 300 ]]Practice and mistakes
Practice: change the unit price to 150 and predict the total for quantity 3. Create a temporary table in a new connection and verify it is absent in another connection. Avoid temporary objects with names that unintentionally shadow permanent tables.