How to count the number of rows that match a condition in Redshift

This article is a part of my "100 data engineering tutorials in 100 days" challenge. (84/100)

It is trivial to count the rows that match a single condition in SQL. We use the WHERE clause and put the condition there. However, how would we count the rows when we want to check multiple conditions simultaneously?

The one way to do that is to use the CASE expression to define the condition and list them as separate columns. For example, if I have a table of product prices products and I want to count the number of products in a few price ranges, I have to do it like this:

    count(CASE WHEN price < 50 THEN 1 END) as price_less_than_50,
    count(CASE WHEN grade >= 50 and grade < 80 THEN 1 END) as price_between_50_80,
    count(CASE WHEN price >= 80 THEN 1 END) as price_80_or_more,

How does it work?

The count function counts the number of non-empty rows, and the CASE expression returns either one or the default value null. Therefore, when the CASE matches the expression, the count function gets one and counts the row as matching the condition. Otherwise, null is passed to the count function, and the function ignores all nulls.

Subscribe to the newsletter and join the free email course.

Remember to share on social media!
If you like this text, please share it on Facebook/Twitter/LinkedIn/Reddit or other social media.

If you want to contact me, send me a message on LinkedIn or Twitter.

Would you like to have a call and talk? Please schedule a meeting using this link.

Bartosz Mikulski
Bartosz Mikulski * MLOps Engineer / data engineer * conference speaker * co-founder of Software Craft Poznan & Poznan Scala User Group

Subscribe to the newsletter and get access to my free email course on building trustworthy data pipelines.