The input set can be an array, a column, or values which are returned from another SQL expression. The sum function is one of the fundamental SQL aggregation functions.

## SQL Sum Function Syntax

The following code snippet shows the syntax for the sum function in SQL:

The function accepts the column or expression with the values whose sum you wish to calculate. We can also use the DISTINCT keyword to skip the duplicate or repeating values.

The function then determines the sum of the provided values and returns a single value.

Let us discuss some basic uses of the sum function.

## Sample Data

Before proceeding, let us look at the layout of the sample data that we wish to query. First, you can check the table schema and insert the statements which are provided in the following:

CREATE TABLE hello.store (

id INTEGER NOT NULL,

product_name STRING NOT NULL,

quantity INTEGER,

price INTEGER NOT NULL,

);

Once created, we can insert the following sample data:

hello.store (id,

product_name,

quantity,

price)

VALUES

(1, "Product 1", 10, 100),

(2, "Product 2", 5, 50),

(3, "Product 3", 20, 200),

(4, "Product 4", 15, 150),

(5, "Product 5", 25, 250),

(6, "Product 6", 30, 300),

(7, "Product 7", 35, 350),

(8, "Product 8", 40, 400),

(9, "Product 9", 45, 450),

(10, "Product 10", 50, 500);

Let us now see some examples on how we can use the sum function in SQL.

## Example 1: Using the Sum Function with a Single Column

We can find the sum of values in a given column using the sum and the column name as shown in the following example:

This should return the total price for all products as follows:

2750

## Example 2: Using the Sun Function with Multiple Columns

We can also create an expression based on multiple table columns in conjunction with the sum() function as shown in the following:

SUM(quantity*price) AS total_stock

FROM

hello.store;

This should return as follows:

96250

## Conclusion

In this tutorial, you learned how to use the SQL SUM function to calculate the sum of the values in a specified column or expression. We often use the sum function in combination with the SELECT statement to calculate the total of a set of values.