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 - GROUPING SETS
Next article icon

PostgreSQL - GROUPING SETS

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 essentially a set of columns by which you want to group your data. Typically, a single aggregate query defines a single grouping set, but with GROUPING SETS, you can define multiple grouping sets in a single query.

Syntax

SELECT     column1,     column2,     aggregate_function(column3) FROM     table_name GROUP BY     GROUPING SETS (         (column1, column2),         (column1),         (column2),         () );

PostgreSQL GROUPING SETS 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: 

PostgreSQL
CREATE TABLE geeksforgeeks_courses(     course_name VARCHAR NOT NULL,     segment VARCHAR NOT NULL,     quantity INT NOT NULL,     PRIMARY KEY (course_name, segment) ); 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); 


Now that our table is set let's look into examples. 

Example 1: Grouping by Course Name and Segment

The following query defines a grouping set of the 'course_name' and 'segment'. It returns the number of products sold by brand and segment. 

Query:

SELECT     course_name,     segment,     SUM (quantity) FROM     geeksforgeeks_courses GROUP BY     course_name,     segment;

Output: 

PostgreSQL GROUPING SETS Example

Explanation: This query groups the data by both course_name and segment. For each combination of 'course_name' and 'segment', it calculates the total quantity of courses sold.

Example 2: Grouping by Course Name

The following query finds the number of courses sold by 'course_name'. It defines a grouping set of the 'course_name':.

Query:

SELECT     course_name,     SUM (quantity) FROM     geeksforgeeks_courses GROUP BY     course_name;

Output: 

PostgreSQL GROUPING SETS Example

Explanation: This query groups the data by 'course_name' only. It calculates the total quantity of courses sold for each course name, regardless of the segment.

Example 3: Grouping by Segment

The following query finds the number of products sold by segment. It defines a grouping set of the segment.

Query: 

SELECT     segment,     SUM (quantity) FROM     geeksforgeeks_courses GROUP BY     segment;

Output: 

PostgreSQL GROUPING SETS Example

Explanation: This query groups the data by segment only. It calculates the total quantity of courses sold for each segment, regardless of the course name.

Example 4: Multiple Grouping Sets in a Single Query

In the following query, we will generate a single result set with the aggregates for all grouping sets.

Query: 

SELECT     GROUPING(course_name) grouping_course,     GROUPING(segment) grouping_segment,     course_name,     segment,     SUM (quantity) FROM     geeksforgeeks_courses GROUP BY     GROUPING SETS (         (course_name, segment),         (course_name),         (segment),         ()     ) ORDER BY     course_name,     segment;

Output: 

PostgreSQL GROUPING SETS Example

Explanation: This query uses the GROUPING function to distinguish between the different grouping sets, providing a more comprehensive analysis of the data.

Important Points About PostgreSQL GROUPING SETS

  • The GROUPING function helps differentiate between aggregated and non-aggregated rows by returning 0 or 1, indicating whether a column is part of the current grouping set.
  • An empty grouping set '()' can be used to calculate the grand total, aggregating all rows regardless of any grouping columns.
  • GROUPING SETS can be combined with CUBE and ROLLUP to produce even more complex and comprehensive result sets.
  • GROUPING SETS allow for complex aggregations that would otherwise require multiple UNION ALL operations.

Next Article
PostgreSQL - GROUPING SETS

R

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

Similar Reads

    PostgreSQL - SELF JOIN
    In PostgreSQL, a SELF JOIN is a powerful technique that allows us to join a table with itself. This type of join is particularly useful for comparing rows within the same table, such as establishing hierarchical relationships or identifying duplicate records. Unlike other joins, there is no specific
    4 min read
    Group By Vs Distinct in PostgreSQL
    When working with PostgreSQL, efficiently organizing and retrieving data is critical for database performance and decision-making. Two commonly used clauses are DISTINCT and GROUP BY that serve distinct purposes in data retrieval. DISTINCT is used to filter out duplicate values, while GROUP BY is em
    6 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 - STRING_AGG() Function
    The STRING_AGG() function in PostgreSQL is a powerful aggregate function used to concatenate a list of strings with a specified separator. This function is essential for combining string values from multiple rows into a single string, making data aggregation more efficient and readable. Let us get a
    2 min read
    PostgreSQL - GROUP BY clause
    The GROUP BY clause in PostgreSQL is an essential tool that allows us to group rows that share the same values in one or more columns. This powerful functionality is commonly used to perform aggregate calculations such as SUM(), COUNT(), AVG(), and more, enabling us to summarize data efficiently. In
    4 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