SUM() Function in MySQL
SUM() function :
This function in MySQL is used to compute the sum of the specified group of values.
Features :
- This function is used to compute the sum of the specified group of values.
- This function comes under Numeric Functions.
- This function accepts only one parameter namely expression.
- This function ignores the null value.
Syntax :
SUM(expression)
Parameter :
This method accepts only one parameter as given below:
- expression: Specified expression which can either be a field or a given formula.
Returns :
It returns the sum of the specified group of values.
Example-1 :
Using SUM() function and getting the output.
CREATE TABLE product09 ( user_id int NOT NULL AUTO_INCREMENT, product_1 VARCHAR(10), product_2 VARCHAR(10), price int, PRIMARY KEY(user_id) ); INSERT product09(product_1, price) VALUES ('rice', 350); INSERT product09(product_2, price) VALUES ('grains', 230); SELECT SUM(price) FROM product09;
Output :
580
Example-2 :
Using SUM() function and finding the sum of all the stated float values.
CREATE TABLE float062 ( user_id int NOT NULL AUTO_INCREMENT, float_val float, PRIMARY KEY(user_id) ); INSERT float062(float_val) VALUES (1.9); INSERT float062(float_val) VALUES (1.1); INSERT float062(float_val) VALUES (3.9); INSERT float062(float_val) VALUES (10.2); INSERT float062(float_val) VALUES (7.9); SELECT SUM(float_val) FROM float062;
Output :
25
Example-3 :
Using SUM() function and getting the output where MRP is less than the sum of all the MRP’s.
CREATE TABLE package77 ( user_id int NOT NULL AUTO_INCREMENT, item VARCHAR(10), mrp int, PRIMARY KEY(user_id) ); INSERT package77(item, mrp) VALUES ('book1', 3); INSERT package77(item, mrp) VALUES ('book2', 350); INSERT package77(item, mrp) VALUES ('book3', 400); SELECT * FROM package77 WHERE mrp < (SELECT SUM(mrp) FROM package77);
Output :
user_id | item | mrp -------------------------------- 1 | book1 | 3 -------------------------------- 2 | book2 | 350 -------------------------------- 3 | book3 | 400
Example-4 :
Using SUM() function and getting the sum of all the (MRP-sales price) values.
CREATE TABLE package72 ( user_id int NOT NULL AUTO_INCREMENT, item VARCHAR(10), mrp int, sp int, PRIMARY KEY(user_id) ); INSERT package72(item, mrp, sp) VALUES ('book1', 250, 240); INSERT package72(item, mrp, sp) VALUES ('book2', 350, 320); INSERT package72(item, mrp, sp) VALUES ('book3', 400, 350); SELECT SUM(mrp-sp) FROM package72;
Output :
90
Application:
This function is used to compute the sum of the specified group of values.