The PostgreSQL ROLLUP clause is a powerful extension to the GROUP BY clause, providing a shortcut for defining multiple grouping sets. When multiple columns are grouped together, they form a grouping set. By organizing and aggregating data hierarchically, ROLLUP creates meaningful summaries without the need for complex subqueries. ROLLUP is particularly useful for generating subtotals and grand totals in reports.
In this article, we will explain the PostgreSQL ROLLUP syntax, explore its practical use cases, and provide multiple examples to demonstrate its functionality. We will also highlight the key differences between ROLLUP and CUBE in PostgreSQL, helping us choose the right operation based on our needs.
What is PostgreSQL ROLLUP?
ROLLUP in PostgreSQL is used to create subtotals and grand totals in the result set. It assumes a hierarchical relationship between the columns and generates only those grouping sets that make sense within that hierarchy. This is different from the CUBE subclause, which generates all possible combinations.
Syntax
SELECT
column1,
column2,
column3,
aggregate(column4)
FROM
table_name
GROUP BY
ROLLUP (column1, column2, column3);
Key Terms
column1, column2, column3
: These are the columns that will be used for grouping.
aggregate(column4)
: This is the aggregate function we want to apply (e.g., SUM
, COUNT
, AVG
).
PostgreSQL ROLLUP Examples
To better understand the concept let's create a new table and proceed to the examples. To create a sample table use the below command. This will help us illustrate how ROLLUP works in various aggregation scenarios.
1. Creation of the Sample table
CREATE TABLE geeksforgeeks_courses(
course_name VARCHAR NOT NULL,
segment VARCHAR NOT NULL,
quantity INT NOT NULL,
PRIMARY KEY (course_name, segment)
);
2. Insertion of values
INSERT INTO geeksforgeeks_courses(course_name, segment, quantity)
VALUES
('Data Structure in Python', 'Premium', 100),
('Algorithm Design in Python', 'Basic', 200),
('Data Structure in Java', 'Premium', 100),
('Algorithm Design in Java', 'Basic', 300);
Example 1: Generating Subtotals and Grand Totals Using ROLLUP
The following query uses the ROLLUP subclause to find the number of products sold by 'course_name'(subtotal) and by all 'course_name' and 'segments' (total) as follows.
Query:
SELECT
course_name,
segment,
SUM (quantity)
FROM
geeksforgeeks_courses
GROUP BY
ROLLUP (course_name, segment)
ORDER BY
course_name,
segment;
Output

Explanation:
This query calculates the sum of quantities for each course_name and segment, and also generates subtotals for each course_name and a grand total across all courses and segments.
Example 2: Partial ROLLUP for Grouping by Segment
In this example, we will modify the ROLLUP to generate subtotals within each segment and across all segments. This demonstrates how ROLLUP allows us to apply partial aggregation.
Query:
SELECT
segment,
course_name,
SUM (quantity)
FROM
geeksforgeeks_courses
GROUP BY
segment,
ROLLUP (course_name)
ORDER BY
segment,
course_name;
Output

Explanation:
This query first groups data by segment and then by course_name within each segment, generating subtotals for each course_name and a total for the entire segment.
Conclusion
The PostgreSQL ROLLUP clause is an important tool for generating hierarchical aggregations in our reports. By using ROLLUP, we can easily calculate subtotals and grand totals for grouped data, making it a must-know feature for any PostgreSQL user working with summary reports. Additionally, it simplifies complex queries by eliminating the need for manual aggregation, saving time and effort in data analysis.
Similar Reads
PostgreSQL - CUBE The CUBE extension of the GROUP BY clause is invaluable for multi-dimensional aggregation. This feature allows analysts and developers to easily perform in-depth analyses of data from multiple perspectives.Let us get a better understanding of the CUBE in PostgreSQL from this article.What is CUBE in
2 min read
PostgreSQL - CASE In PostgreSQL, the CASE expression allows you to perform conditional operations within your SQL queries. It evaluates a list of conditions and returns a result when the first condition is met. If no conditions are met, it returns the result specified in the ELSE clause.Let us better understand the C
3 min read
PostgreSQL - While Loops When working with PostgreSQL, knowing how to efficiently use loops can be essential for running iterative operations. PostgreSQLâs WHILE loop allows developers to repeatedly execute a block of code as long as a specified condition remains true. PostgreSQL provides the loop statement which simply def
4 min read
Grouping Data with ROLLUP in PostgreSQL In database management, reducing and compressing data is one of the most significant jobs. PostgreSQL, which is an open-source, stable relational database management system, boosts many features that are meant to help in this regard. Another element is ROLLUP which maintains the hierarchical data ag
4 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 while
2 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 Synt
3 min read
PostgreSQL COALESCE Handling NULL values effectively is important in database management, and PostgreSQL offers a powerful function called COALESCE to address this issue. The COALESCE function returns the first non-null argument among its parameters, making it particularly useful in SELECT statements.In this article, w
5 min read
PostgreSQL - GROUPING SETS In PostgreSQL, the GROUPING SETS feature allows users to generate result sets that are equivalent to those produced by the UNION ALL of multiple GROUP BY clauses. This feature is highly useful for creating complex reports with multiple levels of aggregation in a single query.A grouping set is essent
3 min read
PostgreSQL Exercises PostgreSQL is a powerful, open-source relational database system that supports complex queries, data types, and performance optimization features. This article provides PostgreSQL practice exercises with solutions, allowing learners to explore how joins, aggregations, triggers, and foreign keys work
15+ min read
Compute a Running Total in Postgresql PostgreSQL is a modern relational database system that is capable of both SQL-oriented relational queries and JSON non-relational queries. It is free and open source. Running total or cumulative sum are very frequent tasks in PostgreSQL, which can be used to deal with sequential data or financial re
5 min read