Search code examples
mysqlgenerated-columns

Stored/Virtual Generated Column- Pros/Cons/Best Practices?


I've read the MySQL Documentation on them, but still not clear on the benefits of Stored/Virtual Generated Columns? What are the pros/cons over storing the same data in an actual column and indexing that into memory? What are the pros/cons, and the best times/examples to when using them are more efficient or better? Thank you!


Solution

  • A good reason to use a stored generated column is when the expression is costly enough that you want to calculate it only when you insert/update the row. A virtual generated column must recalculate the expression every time you run a query that reads that column.

    The manual confirms this:

    Stored generated columns can be used as a materialized cache for complicated conditions that are costly to calculate on the fly.

    Besides that, there are some uses of generated columns that require the column to be stored. They don't work with virtual generated columns. For example, you need to use a stored generated column if you want to create a foreign key or a fulltext index on that generated column.