Add a new column to table and fill it with the data of two other columns of the same table in MySQL?


Let us first create a table −

mysql> create table DemoTable
(
   Price int,
   Quantity int
);
Query OK, 0 rows affected (0.71 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(45,3);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(90,2);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(440,1);
Query OK, 1 row affected (0.09 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+----------+
| Price | Quantity |
+-------+----------+
|    45 |        3 |
|    90 |        2 |
|   440 |        1 |
+-------+----------+
3 rows in set (0.00 sec)

Following is the query to add a new column to the table and fill with the data of 2 other columns. Here, we have added new column TotalAmount and the data in it is the multiplication of the values from the first two columns −

mysql> select Price,Quantity, Price*Quantity AS TotalAmount from DemoTable;

This will produce the following output −

+-------+----------+-------------+
| Price | Quantity | TotalAmount |
+-------+----------+-------------+
|    45 |        3 |         135 |
|    90 |        2 |         180 |
|   440 |        1 |         440 |
+-------+----------+-------------+
3 rows in set (0.00 sec)

Updated on: 30-Sep-2019

782 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements