Understanding Generated Columns in MySQL

Generated columns in MySQL allow database administrators and developers to store computed values automatically without manually updating them. This article explains how generated columns work, the differences between virtual and stored types, and how they improve query performance and data integrity in a database schema.

What is a Generated Column?

A generated column is a column whose value is automatically calculated from an expression rather than being directly inserted or updated by a user. The expression can reference other columns in the same table, allowing the database to maintain derived data automatically.

For example, if a table has columns for price and quantity, a generated column can automatically calculate the total_cost using the expression price * quantity.

Types of Generated Columns

MySQL supports two types of generated columns, which differ in how they are stored and processed:

1. Virtual Generated Columns (VIRTUAL)

2. Stored Generated Columns (STORED)

Key Benefits of Generated Columns

Integrating generated columns into a MySQL schema provides several distinct advantages:

Syntax Example

To define a generated column, use the GENERATED ALWAYS AS clause in your CREATE TABLE or ALTER TABLE statement:

CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    price DECIMAL(10, 2) NOT NULL,
    discount DECIMAL(3, 2) DEFAULT 0.00,
    discounted_price DECIMAL(10, 2) GENERATED ALWAYS AS (price * (1 - discount)) STORED
);

In this schema, whenever a row is inserted or updated, MySQL automatically calculates the discounted_price and stores it physically on the disk.