mysql
  1. mysql-sum

sum() - MySQL Aggregate Function

In MySQL, the sum() function is used to calculate the sum of all values in a particular column. It is an aggregate function that returns a single value, which is the sum of all values in the specified column.

Syntax

The syntax for using the sum() function is as follows:

SELECT SUM(column_name) 
FROM table_name;

Here, column_name refers to the name of the column where you want to find the sum, and table_name refers to the name of the table.

Example

Let's say we have a table called order_items that contains information about the items ordered by customers. We want to find the total amount of all orders. Here's how we can use the sum() function to do this:

SELECT SUM(price * quantity) AS total_amount 
FROM order_items;

This query multiplies the price and quantity columns for each row and calculates the sum of all values. We are using the AS keyword to create an alias for the result, which is total_amount. This makes the output more readable.

Output

When we run the above example query, the output will be a single value, which is the sum of all the values in the specified column:

+-------------+
| total_amount|
+-------------+
|  2567.80    |
+-------------+

Explanation

In the example above, we used the sum() function to calculate the total amount of all orders in the order_items table. We multiplied the price and quantity columns to get the total cost of each order item, and then used the sum() function to add up all these values.

Use

The sum() function is useful when you need to find the total sum of all values in a particular column, such as the total revenue generated by an e-commerce website or the total number of hours worked by employees.

Important Points

  • The values in the specified column must be numeric for the sum() function to work.
  • You can use the AS keyword to give an alias to the result of the sum() function.
  • If the specified column contains null values, the sum() function will ignore them and return the sum of non-null values.

Summary

In this tutorial, we discussed the sum() function in MySQL. We covered the syntax, example, output, explanation, use, and important points of the sum() function. With this knowledge, you can now use the sum() function to calculate the sum of all values in a specified column of your MySQL table.

Published on: