SUM

Beginner

In SQL, the SUM() function is an aggregate function used to calculate the sum of values in a specified column of a table or the sum of a set of numerical values.

Basic syntax

The basic syntax of the SUM() function is as follows:

SELECT SUM(column_name)
FROM table_name
WHERE condition
  • SUM(column_name): This calculates the sum of values in the specified column_name.
  • table_name: This is the name of the table from which you want to retrieve the data.
  • condition: This is an optional condition that specifies which rows to include in the sum calculation.

Examples

Consider a table named sales with the following structure and data:

sales_id product_id quantity amount
1 101 2 100
2 102 3 150
3 101 1 50
4 103 2 120

To calculate the total amount of sales, you can use the SUM() function as follows:

SELECT SUM(amount) AS total_sales
FROM sales

This query will return the sum of the amount column, which is 420, representing the total sales amount.

Subtraction

SQL does not have a specific "subtract" function, but subtraction is achieved using the minus (-) operator. The minus operator is used to subtract one numeric value from another.

Syntax:

SELECT column1 - column2 AS result
FROM your_table;

Example:

SELECT 10 - 5 AS subtraction_result;
-- Output: 5

SELECT column1, column2, column1 - column2 AS subtraction_result
FROM your_table;

You can also perform subtraction with column values or variables, and you can use parentheses to control the order of operations if needed.

Example with Column Values:

SELECT column1, column2, (column1 - column2) AS subtraction_result
FROM your_table;

It's important to note that subtraction works with both integers and floating-point numbers. If you subtract two integers, the result will be an integer. If at least one operand is a floating-point number, the result will be a floating-point number.

SELECT 7 - 3 AS integer_subtraction;
-- Output: 4

SELECT 7.0 - 3.5 AS float_subtraction;
-- Output: 3.5