You can use aggregate function SUM() from MySQL for this. Let us first create a table −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Amount int ); Query OK, 0 rows affected (0.65 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Amount) values(400); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(Amount) values(10); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(Amount) values(50); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(Amount) values(500); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(Amount) values(80); Query OK, 1 row affected (0.09 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+ | Id | Amount | +----+--------+ | 1 | 400 | | 2 | 10 | | 3 | 50 | | 4 | 500 | | 5 | 80 | +----+--------+ 5 rows in set (0.00 sec)
Here is the query to get the sum of rows (not all) out of MySQL table −
mysql> select sum(Amount) from DemoTable where Id in(1,4,5);
This will produce the following output −
+-------------+ | sum(Amount) | +-------------+ | 980 | +-------------+ 1 row in set (0.00 sec)