How can I calculate the total value of products from my MySQL product table?


Let us first create a table −

mysql> create table DemoTable
   (
   ProductId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ProductQuantity int,
   ProductPrice int
   );
Query OK, 0 rows affected (0.19 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(ProductQuantity,ProductPrice) values(10,100);
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(ProductQuantity,ProductPrice) values(5,11);
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(ProductQuantity,ProductPrice) values(3,140);
Query OK, 1 row affected (0.05 sec)

mysql> insert into DemoTable(ProductQuantity,ProductPrice) values(2,450);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+-----------------+--------------+
| ProductId | ProductQuantity | ProductPrice |
+-----------+-----------------+--------------+
| 1         | 10              | 100          |
| 2         | 5               | 11           |
| 3         | 3               | 140          |
| 4         | 2               | 450          |
+-----------+-----------------+--------------+
4 rows in set (0.00 sec)

Following is the query to calculate total value of products −

mysql> select sum(ProductQuantity*ProductPrice) as Total_of_Products from DemoTable;

This will produce the following output −

+-------------------+
| Total_of_Products |
+-------------------+
| 2375              |
+-------------------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

457 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements