How can we have multiple virtuals GENERATED COLUMNS in MySQL table with CREATE TABLE statement?


It is quite possible to add multiple virtual generated columns in a MySQL table. It can be illustrated with the following example as follows −

Example

mysql> Create table profit(cost int, price int, profit int AS (price-cost), price_revised int AS (price-2));
Query OK, 0 rows affected (0.73 sec)

mysql> Describe profit;
+---------------+---------+------+-----+---------+-------------------+
| Field         | Type    | Null | Key | Default | Extra             |
+---------------+---------+------+-----+---------+-------------------+
| cost          | int(11) | YES  |     | NULL    |                   |
| price         | int(11) | YES  |     | NULL    |                   |
| profit        | int(11) | YES  |     | NULL    | VIRTUAL GENERATED |
| price_revised | int(11) | YES  |     | NULL    | VIRTUAL GENERATED |
+---------------+---------+------+-----+---------+-------------------+
4 rows in set (0.00 sec)

mysql> Insert into profit(Cost, Price) values(100,110);
Query OK, 1 row affected (0.04 sec)

mysql> Insert into profit(Cost, Price) values(200,220);
Query OK, 1 row affected (0.04 sec)

mysql> Select * from profit;
+------+-------+--------+---------------+
| cost | price | profit | price_revised |
+------+-------+--------+---------------+
| 100  | 110   | 10     | 108           |
| 200  | 220   | 20     | 218           |
+------+-------+--------+---------------+
2 rows in set (0.00 sec)

Updated on: 22-Jun-2020

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements