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.
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.sales
order_id | product_name | sales_amount | order_date |
---|---|---|---|
1 | Laptop | 1200 | 2023-01-15 |
2 | Smartphone | 800 | 2023-02-03 |
3 | Headphones | 150 | 2023-02-10 |
4 | Laptop | 1000 | 2023-03-05 |
5 | Smartphone | 900 | 2023-03-18 |
Now, let’s use this table for the examples in the tutorial.
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;
sales_amount |
---|
4050 |
Let’s explore additional examples using the “sales” database to showcase the versatility of the SQL SELECT SUM command.
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_category | total_sales |
---|---|
Electronics | 3050 |
Accessories | 150 |
This query groups the sales data by product category, providing a clear breakdown of total sales for each category.
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;
month | total_sales |
---|---|
1 | 1200 |
2 | 950 |
3 | 1900 |
Here, the query extracts the month from the order_date and presents the total sales for each month.
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_name | average_sales | order_count |
---|---|---|
Laptop | 1100 | 2 |
Smartphone | 850 | 2 |
Headphones | 150 | 1 |
This query showcases the combined use of AVG and COUNT along with the SELECT SUM command for a comprehensive analysis.