Addition in SQL using SELECT SUM command

SQL

The SELECT SUM statement is like a virtual calculator for our database, allowing us to effortlessly calculate the total of values in a specific column.

Syntax

The basic syntax of the SELECT SUM statement is as follows:

SELECT SUM(column_name) AS total_sum
FROM table_name;
  • column_name: The name of the column for which you want to calculate the sum.
  • total_sum: An alias assigned to the result of the SUM operation for better readability.

Database Table: sales

order_idproduct_namesales_amountorder_date
1Laptop12002023-01-15
2Smartphone8002023-02-03
3Headphones1502023-02-10
4Laptop10002023-03-05
5Smartphone9002023-03-18

Now, let’s use this table for the examples in the tutorial.

Basic Example

Let’s use the SUM function to calculate the total sales amount from the “sales” table:

SELECT SUM(sales_amount) AS total_sales
FROM sales;

Output

sales_amount
4050

Let’s explore additional examples using the “sales” database to showcase the versatility of the SQL SELECT SUM command.

Example 1: Total Sales for Each Product Category

Suppose you want to know the total sales for each product category. You can use the GROUP BY clause to achieve this:

SELECT product_category, SUM(sales_amount) AS total_sales
FROM sales
GROUP BY product_category;
product_categorytotal_sales
Electronics3050
Accessories150

This query groups the sales data by product category, providing a clear breakdown of total sales for each category.

Example 2: Monthly Sales Totals

If you want to analyze sales on a monthly basis, you can extract the month from the order_date and calculate the total sales for each month:

SELECT EXTRACT(MONTH FROM order_date) AS month, SUM(sales_amount) AS total_sales
FROM sales
GROUP BY month;
monthtotal_sales
11200
2950
31900

Here, the query extracts the month from the order_date and presents the total sales for each month.

Example 3: Combined Aggregation with AVG and COUNT

You can combine multiple aggregation functions in a single query. For instance, finding the average sales and the number of orders for each product:

SELECT product_name, AVG(sales_amount) AS average_sales, COUNT(order_id) AS order_count
FROM sales
GROUP BY product_name;
product_nameaverage_salesorder_count
Laptop11002
Smartphone8502
Headphones1501

This query showcases the combined use of AVG and COUNT along with the SELECT SUM command for a comprehensive analysis.