Get the sum of a column in all MySQL rows?


Use aggregate function SUM() to get the sum of a column in al rows. 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.20 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Amount) values(50);
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable(Amount) values(60);
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(Amount) values(70);
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+--------+
| Id | Amount |
+----+--------+
|  1 |     50 |
|  2 |     60 |
|  3 |     70 |
+----+--------+
3 rows in set (0.00 sec)

Following is the query to get the sum of all rows in MySQL.

mysql> select sum(Amount) from DemoTable;

This will produce the following output −

+-------------+
| sum(Amount) |
+-------------+
|         180 |
+-------------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements