Use aggregate function sum() to sum the elements of a column in MySQL. The syntax is as follows −
select sum(yourColumnName1) as anyVariableName1,sum(yourColumnName2) as anyVariableName2,sum(yourColumnName3) as anyVariableName3,............N from yourTableName;
To understand the above syntax, let us create a table. The following is the query to create a table −
mysql> create table SumDemoOnColumns −> ( −> First int, −> Second int, −> Third int −> ); Query OK, 0 rows affected (0.56 sec)
Insert some data in the table using insert command. The query is as follows −
mysql> insert into SumDemoOnColumns values(10,20,30); Query OK, 1 row affected (0.18 sec) mysql> insert into SumDemoOnColumns values(40,50,60); Query OK, 1 row affected (0.32 sec) mysql> insert into SumDemoOnColumns values(70,80,90); Query OK, 1 row affected (0.10 sec) mysql> insert into SumDemoOnColumns values(100,110,120); Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from SumDemoOnColumns;
The following is the output −
+-------+--------+-------+ | First | Second | Third | +-------+--------+-------+ | 10 | 20 | 30 | | 40 | 50 | 60 | | 70 | 80 | 90 | | 100 | 110 | 120 | +-------+--------+-------+ 4 rows in set (0.00 sec)
The following is the query to get sum of columns −
mysql> select sum(First) as First,sum(Second) as Second,sum(Third) as Third from SumDemoOnColumns;
The following is the output −
+-------+--------+-------+ | First | Second | Third | +-------+--------+-------+ | 220 | 260 | 300 | +-------+--------+-------+ 1 row in set (0.00 sec)