maria-db
  1. maria-db-sum-function

SUM Function - (MariaDB Aggregate Functions)

The SUM function in MariaDB is an aggregate function that allows you to sum a column of numeric values in a table. It is frequently used in SQL queries to perform calculations on large datasets.

Syntax

The basic syntax for using the SUM function is as follows:

SELECT SUM(column_name) FROM table_name;

Here, column_name is the name of the column you want to sum, and table_name is the name of the table that contains the column.

Example

Consider a table called sales that contains the following data:

id | date       | product | quantity | price
---+------------+---------+----------+--------
1  | 2021-09-01 | A       | 10       | 5.99
2  | 2021-09-02 | B       | 15       | 4.99
3  | 2021-09-03 | A       | 5        | 6.99
4  | 2021-09-04 | B       | 20       | 3.99

To calculate the total sales for all products, we can use the SUM function as follows:

SELECT SUM(quantity * price) as total_sales FROM sales;

The query above multiplies the quantity and price columns of each row and sums the resulting values. The resulting sum is given an alias called total_sales.

Output

The output of the query above would be:

total_sales
------------
249.20

Explanation

In the example above, we used the SUM function to calculate the total sales for all products in the sales table. We first multiplied the quantity and price columns for each row to calculate the total sales for that row. The SUM function then summed the total sales for each row to provide the total sales for all products.

Use

The SUM function is useful for calculating totals and subtotals in SQL queries. It can be used with other aggregate functions and GROUP BY clauses to perform calculations on subsets of data.

Important Points

  • The SUM function in MariaDB is an aggregate function that allows you to sum a column of numeric values in a table.
  • It is frequently used in SQL queries to perform calculations on large datasets.
  • The syntax for using the SUM function is SELECT SUM(column_name) FROM table_name;
  • The SUM function can be used with other aggregate functions and GROUP BY clauses to perform calculations on subsets of data.

Summary

In summary, the SUM function in MariaDB is a powerful tool for calculating totals and subtotals in SQL queries. It is useful for performing complex calculations on large datasets and can be used in conjunction with other aggregate functions and GROUP BY clauses to analyze subsets of data.

Published on: