PostgreSQL 9.4: Using FILTER CLAUSE, multiple COUNT(*) in one SELECT Query for Different Groups

PostgreSQL 9.4 has introduced one of the very good FILTER CLAUSE which is used to apply filters in aggregate functions.

Using FILTER, You can use different types of aggregate functions without applying any GROUP BY CLAUSE.

Now Imagine, that I have one Student table and I want total number of Students based different grades.
What happened without FILTER CLAUSE, We have to perform this calculation in the individual SELECT query.

But with the use of FILTER CLAUSE we can perform aggregation based on different FILTER values in a single SQL Query.

Below is a small demonstration of this:

Create one Student table with sample data:

Apply FILTER clause to count number of Students based on Marks:

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

Sort by:   newest | oldest | most voted
Bruno Felipe

It’s very nice post!!!!
can you post about cube and group cube?

Bob Smith

Thanks for posting about a lessor known feature. FYI – The way you have set up the BETWEEN would give incorrect results if any student has a mark that is 60 or 80. BETWEEN is inclusive so a mark of 60 would be counted for both TotalGrade_C and TotalGrade_B. Add the following and re-run the select:

insert into tbl_Students
values (13, ‘Bob’, 60);