⚠️ This post links to an external website. ⚠️
Doing a
COUNT()in SQL is pretty simple, but sometimes you want to return several counts at once with different filters. To achieve this, you would typically do multiple queries, optionally with aWITHquery.Thankfully, there's a way simpler way to do this in PostgreSQL, with
FILTER.Let's consider we have a simple table (
racoons) with a few fields, and we want to return acaretaker_id, the total number of racoons taken care by this person, and the number of racoons that have been released to the wilds.It's as simple as this:
SELECT r.caretaker_id,COUNT(*) as total,COUNT(*) FILTER (WHERE released = true) as releasedFROM racoons rGROUP BY r.caretaker_id;
continue reading on mbuffa.github.io
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.