PostgreSQL: Multiple GROUP BY using GROUPING SETS in Single SQL Query

In this post, I am sharing one demonstration of PostgreSQL GROUPING SETS.
This is very useful for PostgreSQL Database Developers who require to perform multiple GROUP BY in one single query.

Now take one example, you want to find the count of Employee based on two columns: Employee Department , Employee Joining Year.
For this query, you have to write different two queries and If you want to combine results of both the query, you should use UNION clause.

But using GROUPING SETS, we can prepare this result into one single query.

Below is a full demonstration of this:

Create a table with Sample data:

Count of Employee, Group By Department column:

Count of Employee, Group By Joining Year:

GROUP BY above two queries using GROUPING SETS:

The Result:

Please share your ideas and opinions about this topic with me, your contribution will add true value to this topic.
If anyone has doubts on this topic then please do let me know by leaving comments or send me an email.

If you like this post, then please share it with others.
Please follow, I will share my experience towards the success of Database Research and Development Activity.

I put up a post every day, please keep reading and learning.
Discover Yourself, Happy Blogging !
Anvesh M. Patel.

More from

Leave a Reply

1 Comment on "PostgreSQL: Multiple GROUP BY using GROUPING SETS in Single SQL Query"

Notify of

Sort by:   newest | oldest | most voted
Bruno Felipe
Bruno Felipe
2 months 3 days ago

Nice post!!! Thanks very much!