Conditional Summation in PostgreSQL
Last Updated :
04 Jul, 2024
PostgreSQL is a powerful tool that includes advanced features in the field of data analysis and database management. One of its significant useful functions is the capacity to carry out conditional summation, which allows users to add up numbers based on given conditions.
This article goes through the concept of conditional summation in PostgreSQL, illustrating its usage and providing practical examples.
What is Conditional Summation
Conditional summation is a type of calculation that involves the summation of data values from a particular dataset using certain conditions or criteria as a basis. SUM() function along with the CASE statement enables us to accomplish the task for PostgreSQL. The CASE statement is the conditional one, which sets up the conditions and returns the result of the first condition that is true.
Syntax:
The syntax for conditional summation in PostgreSQL can be summarized as follows:
SELECT SUM(CASE
WHEN condition1 THEN value1
WHEN condition2 THEN value2
...
ELSE default_value
END) AS sum_result
FROM table_name;
In this syntax:
- condition1, condition2, etc., represent the conditions to be evaluated.
- value1, value2, etc., represent the values to be summed if the corresponding condition is true.
- default_value is the value returned if none of the conditions are met.
- table_name is the name of the table from which data is being retrieved.
Now let's start by creating a table and inserting some sample data into it. We'll then proceed to demonstrate some example queries for conditional summation in PostgreSQL.
Create a table named sales and insert some data into it.
CREATE TABLE sales (
product_id SERIAL PRIMARY KEY,
quantity_sold INTEGER,
unit_price NUMERIC,
category VARCHAR(50)
);
INSERT INTO sales (quantity_sold, unit_price, category) VALUES
(10, 15.50, 'Electronics'),
(5, 20.25, 'Electronics'),
(8, 10.75, 'Clothing'),
(15, 7.99, 'Clothing'),
(20, 5.50, 'Home Appliances'),
(10, 12.75, 'Home Appliances');
Output:
You can see the table content below:
Sales TableExample Queries of Conditional Summation
We have our table set up with some sample data, let's proceed to demonstrate some example queries for conditional summation.
Example 1: Total sales amount for each category, considering only positive quantities sold.
Query:
SELECT category,
SUM(CASE
WHEN quantity_sold > 0 THEN quantity_sold * unit_price
ELSE 0
END) AS total_sales
FROM sales
GROUP BY category;
Explanation:
- It groups the data by the category column.
- For each group (category), it calculates the total sales by summing up the product of quantity_sold and unit_price for each sale, but only if quantity_sold is greater than 0. Otherwise, it adds 0 to the sum.
- It gives the calculated sum an alias total_sales.
Output:
This query will be a table with two columns: category and total_sales. Each row in the output represents a category along with the total sales for that category.
Total sales amount for each categoryExample 2: Total sales amount for each category, considering only sales with a unit price greater than $10:
Query:
SELECT category,
SUM(CASE
WHEN unit_price > 10 THEN quantity_sold * unit_price
ELSE 0
END) AS total_sales
FROM sales
GROUP BY category;
Explanation:
- It groups the data by the category column.
- For each group (category), it calculates the total sales by summing up the product of quantity_sold and unit_price for each sale, but only if the unit_price is greater than 10. Otherwise, it adds 0 to the sum.
- It gives the calculated sum an alias total_sales.
Output:
Each row in the output represents a category along with the total sales for that category, considering only sales where the unit price is greater than 10.
Total sales amount where sales with a unit price greater than 10Example 3: Total sales amount for each category, considering only sales of electronics.
Query:
SELECT category,
SUM(CASE
WHEN category = 'Electronics' THEN quantity_sold * unit_price
ELSE 0
END) AS total_sales
FROM sales
GROUP BY category;
Explanation:
- It groups the sales data by the category column.
- For each group (category), it calculates the total sales by summing up the product of quantity_sold and unit_price for each sale within the 'Electronics' category. For all other categories, it adds 0 to the sum.
- It gives the calculated sum an alias total_sales.
Output:
Each row in the output represents a category, and for the 'Electronics' category, it displays the total sales amount, while for other categories, it displays 0 as the total sales.
Total sales amount considering only sales of electronicsExample 4: Total sales amount for each category, considering only sales where the quantity sold is greater than 5.
Query:
SELECT category,
SUM(CASE
WHEN quantity_sold > 5 THEN quantity_sold * unit_price
ELSE 0
END) AS total_sales
FROM sales
GROUP BY category;
Explanation:
- It groups the data by the category column.
- For each group (category), it calculates the total sales by summing up the product of quantity_sold and unit_price for each sale where quantity_sold is greater than 5. If quantity_sold is not greater than 5, it adds 0 to the sum.
- It assigns the calculated sum an alias total_sales.
Output:
Each row in the output represents a category along with the total sales for that category, considering only sales where the quantity sold is greater than 5.
Total sales amount only sales where the quantity sold is greater than 5Conclusion
A conditional summation in PostgreSQL allows a way to do data aggregation by calculating the total data based on declared conditions. The combination of SUM() function and CASE statement gives users the flexibility of customizing their summation requests by considering specific requirements. Regardless of whether it is used for analyzing sales data, financial transactions or any other dataset, conditional summation remains as a very useful and essential tool in the PostgreSQL toolbox at all times.
Similar Reads
Conditional Summation in SQL
In data manipulation, SQL (Structured Query Language) stands as a powerful tool for extracting, transforming, and analyzing data stored in relational databases. Among its numerous functionalities, SQL provides robust capabilities for summation operations, allowing users to aggregate data according t
5 min read
Conditional Summation in PL/SQL
Conditional Summation is a process of calculating a sum based on some specific criteria or condition. Calculating "conditional summation" can have lots of use cases. In financial sectors, it allows us to calculate the total or average of a specific category. Similarly in educational sectors, conditi
5 min read
Conditional Summation
Users can determine the total of the values in a column depending on certain conditions by using MySQL's Conditional Summation feature. By enabling users to do calculations on data subsets that satisfy particular needs this feature improves data analysis and manipulating capabilities. One's capacity
3 min read
PostgreSQL - SUM() Function
The SUM() function in PostgreSQL is used to calculate the sum of values in a numeric column. This article will guide you through the syntax, important considerations, and practical examples of using the SUM() function in PostgreSQL. SyntaxSUM(column) The following points need to be kept in mind whil
2 min read
PostgreSQL MIN() Function
The MIN() function in PostgreSQL is an essential aggregate function that returns the minimum value in a set of values. This function is highly useful in various data analysis and reporting tasks, allowing you to quickly identify the smallest values in your datasets. Let us better understand the MIN(
2 min read
How to Use Count With Condition in PostgreSQL?
In PostgreSQL, the COUNT() function serves as a tool for tallying the number of records within a table. This article aims to address this query, delving into the nuances and implications of integrating conditions into the COUNT() function in PostgreSQL. The COUNT() function in PostgreSQL is traditio
4 min read
SQL | Conditional Expressions
In SQL, conditional expressions are essential for making decisions based on certain conditions directly within queries. These expressions allow us to apply business logic, to return values based on conditions, and transform data without using complex procedures. The CASE, DECODE, COALESCE, GREATEST,
4 min read
PostgreSQL - UNION operator
The PostgreSQL UNION operator is a powerful tool used to combine result sets from multiple queries into a single result set. It helps in consolidating data from different sources, making it easier to analyze and report. From this article, we can better understand the UNION Operator in PostgreSQL Syn
3 min read
Python PostgreSQL - Join
In this article, we are going to see join methods in PostgreSQL using pyscopg2 in Python. Let's see the type of joins supported in PostgreSQL. Types of join:Inner joinFull join (outer join)Left joinRight joinCross join Tables for demonstration: Table 1: Employee table Table 2: Dept table The psycopg
3 min read
PostgreSQL - Continue
The CONTINUE statement in PostgreSQL is used to prematurely skip the current iteration of a loop and proceed directly to the next iteration. This functionality applies to all types of loops, including unconditional loops, WHILE loops, and FOR loops. Let us get a better understanding of the CONTINUE
3 min read