Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Understand MySQL generated columns. Compare VIRTUAL and STORED options, index computed JSON attributes, and accelerate expressions without application code.
Quick answer
MySQL generated columns evaluate expressions automatically from other columns in the same row. VIRTUAL generated columns calculate values on read and consume zero disk space, while STORED generated columns calculate values on write and store results physically on disk. Both options support secondary B-tree indexes.
FAQs
Does adding a VIRTUAL generated column lock the table in MySQL?
No. Adding a VIRTUAL column in MySQL 5.7+ and 8.0 is an instant metadata operation that does not lock writes or rewrite table data.
Can I index a VIRTUAL generated column in MySQL?
Yes. MySQL fully supports creating secondary B-tree indexes on VIRTUAL generated columns.
Can a generated column reference another generated column in MySQL?
No. MySQL generated column expressions can only reference base physical columns in the same table, not other generated columns.
What happens if I update a base column referenced by a generated column?
MySQL automatically updates the value of the generated column (and any secondary indexes defined on it) during the update transaction.
Build fast text search directly in PostgreSQL without external search engines. Master to_tsvector, to_tsquery, relevance ranking with ts_rank, and GIN indexes.
In relational database design, storing calculated values directly in tables violates normalization principles and risks data drift if parent columns change without recalculating derived fields. However, recalculating complex formulas or parsing JSON keys in every query consumes excessive CPU and prevents index usage.
MySQL solves this conflict with generated columns (also known as computed columns). Generated columns allow you to define a column as an automated deterministic expression. Crucially, MySQL permits secondary indexes on virtual generated columns, allowing you to index JSON properties without duplicating raw storage.
VIRTUAL vs STORED generated columns
When you define a generated column in MySQL, you must choose between two storage modes: VIRTUAL or STORED.
VIRTUAL (default): Values are not stored on disk. When a query reads the column, MySQL calculates the expression on the fly. Adding a virtual column is an instantaneous metadata-only change that requires zero table rewrite.
STORED: Values are calculated and physically written to disk when the row is inserted or updated. The column consumes disk space and incurs write I/O, but reads avoid on-the-fly CPU recalculation.
Syntax for VIRTUAL and STORED columns
CREATE TABLE retail_orders ( order_id INT AUTO_INCREMENT PRIMARY KEY, unit_price DECIMAL(10, 2) NOT NULL, quantity INT NOT NULL, discount_rate DECIMAL(4, 2) NOT NULL DEFAULT 0.00, -- VIRTUAL generated column: calculated at read time, 0 disk space subtotal DECIMAL(12, 2) GENERATED ALWAYS AS (unit_price * quantity) VIRTUAL, -- STORED generated column: calculated at write time, stored on disk net_total DECIMAL(12, 2) GENERATED ALWAYS AS ( (unit_price * quantity) * (1 - discount_rate) ) STORED);
According to the MySQL generated columns documentation, expressions must be deterministic. You cannot call non-deterministic functions like NOW(), RAND(), or UUID(), nor can you reference subqueries or other generated columns.
Indexing virtual columns: the game-changing feature
The most compelling capability in MySQL is that you can build secondary B-tree indexes directly on VIRTUAL generated columns. The table heap stores zero redundant bytes, but the secondary index B-tree indexes the precomputed expression!
Creating an index on a virtual column
-- Add index on virtual subtotal columnCREATE INDEX idx_retail_orders_subtotal ON retail_orders (subtotal);-- This query performs an index range scan on idx_retail_orders_subtotal:EXPLAIN SELECT order_id, quantityFROM retail_ordersWHERE subtotal > 500.00;
As detailed in MySQL documentation on secondary indexes on generated columns, when an indexed virtual column is updated, InnoDB updates the secondary index B-tree leaf page during the write transaction, ensuring index lookups execute instantly.
Indexing nested JSON data with virtual columns
Modern applications frequently store semi-structured JSON payloads in MySQL. Searching for a specific attribute inside a JSON document normally forces MySQL to perform a full table scan and parse every document with JSON_EXTRACT().
Pairing generated columns with functional indexing provides a clean solution: extract the JSON property into a virtual column and index that column.
Indexing JSON documents with generated columns
CREATE TABLE user_profiles ( user_id INT AUTO_INCREMENT PRIMARY KEY, profile_data JSON NOT NULL, -- Extract 'postal_code' from JSON document into virtual column postal_code VARCHAR(10) GENERATED ALWAYS AS ( JSON_UNQUOTE(JSON_EXTRACT(profile_data, '$.address.postal_code')) ) VIRTUAL, -- Shorthand JSON arrow syntax in MySQL 8.0+: country_code VARCHAR(2) GENERATED ALWAYS AS ( profile_data->>'$.address.country' ) VIRTUAL, -- Index the extracted virtual columns INDEX idx_user_postal (postal_code), INDEX idx_user_country (country_code));-- Fast index lookup on JSON property:SELECT user_id FROM user_profilesWHERE postal_code = '94105';
In almost all production scenarios, choose VIRTUAL. It costs zero additional disk storage and adding the column is an instant metadata operation. If you need fast searches on the expression, simply add a secondary index to the virtual column.
Reserve STORED generated columns for cases where the expression is mathematically CPU-intensive (such as hashing or complex trigonometric formulas) and you read the column frequently without an index.
Actionable checklist for MySQL generated columns
Default to VIRTUAL: use VIRTUAL generated columns to save disk space and avoid table rewrite locks during creation.
Add secondary indexes: create indexes on virtual columns that appear in WHERE, ORDER BY, or GROUP BY clauses.
Use JSON arrow operator: use ->> (inline JSON_UNQUOTE) for clean, readable JSON property extraction in MySQL 8.0+.
Verify expression determinism: confirm expressions avoid volatile functions like RAND() or CURRENT_TIMESTAMP().
Check data type casting: explicitly declare the target data type (VARCHAR, INT, DECIMAL) when defining the generated column.
Profile insert performance: monitor write throughput when indexing multiple virtual columns on high-volume tables.
Wrapping up
MySQL generated columns combine normalization hygiene with query performance. By extracting computed formulas and nested JSON properties into indexed virtual columns, you eliminate expensive runtime calculations without bloating raw table storage. Format your schema definitions and complex database scripts with sqlfmt for clean team collaboration.