PostgreSQL - GROUPING SETS
Last Updated :
01 Aug, 2024
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:

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:

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:

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:

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.
Similar Reads
PostgreSQL Tutorial In this PostgreSQL tutorial youâll learn the basic data types(Boolean, char, text, time, int etc.), Querying and Filtering techniques like select, where, in, order by, etc. managing and modifying the tables in PostgreSQL. Weâll cover all the basic to advance concepts of PostgreSQL in this tutorial.
8 min read
PostgreSQL DATEDIFF Function PostgreSQL doesnât have a DATEDIFF function like some other databases, but you can still calculate the difference between dates using simple subtraction. This approach allows you to find out how many days, months, or years separate two dates. In this article, we'll explore how to compute date differ
6 min read
PostgreSQL - Data Types PostgreSQL is a powerful, open-source relational database management system that supports a wide variety of data types. These data types are essential for defining the nature of the data stored in a database column. which allows developers to define, store, and manipulate data in a way that aligns w
5 min read
PostgreSQL - Psql commands PostgreSQL, or Postgres, is an object-relational database management system that utilizes the SQL language. PSQL is a powerful interactive terminal for working with the PostgreSQL database. It enables users to execute queries efficiently and manage databases effectively.Here, we highlight some of th
2 min read
Top 50 PostgreSQL Interview Questions and Answers Are you preparing for a PostgreSQL interview? PostgreSQL is a powerful open-source relational database management system (RDBMS) that is well-known for its reliability, scalability, and rich set of features. Itâs a favorite among developers and businesses alike, making it essential to master if we w
15+ min read
PostgreSQL - Create Database Creating a database in PostgreSQL is an important task for developers and database administrators to manage data effectively. PostgreSQL provides multiple ways to create a database, catering to different user preferences, whether through the command-line interface or using a graphical interface like
5 min read
How to Dump and Restore PostgreSQL Database? PostgreSQL remains among the most efficient and widely applied open-source relational database management systems. It provides the superior function of saving, configuring, and extracting information most effectively. In the process of migrating data, creating backups, or transferring databases betw
6 min read
PostgreSQL - SERIAL When working with PostgreSQL, we need to create tables with unique primary keys. PostgreSQL offers a powerful feature known as the SERIAL pseudo-type which simplifies generating auto-incrementing sequences for columns. In this article, weâll learn about the PostgreSQL SERIAL pseudo-type by explain h
5 min read
PostgreSQL - DISTINCT ON expression The DISTINCT ON clause in PostgreSQL allows us to retrieve unique rows based on specific columns by offering more flexibility than the standard DISTINCT clause. DISTINCT ON allow us to specify which row to keep for each unique value based on an ORDER BY clause. This is particularly useful for select
5 min read
PostgreSQL Connection String A connection string is an essential component that enables applications to communicate with databases or other data sources by providing the necessary configuration details. It consolidates critical information such as the server address, database name, user credentials, and additional parameters li
4 min read