Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
PostgreSQL - ROLLUP
Next article icon

PostgreSQL - ROLLUP

Last Updated : 18 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

PostgreSQL ROLLUP Example

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

PostgreSQL ROLLUP Example

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.


Next Article
PostgreSQL - ROLLUP

R

RajuKumar19
Improve
Article Tags :
  • PostgreSQL
  • Databases
  • postgreSQL-grouping-sets

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences