How to count the number of rows that match a condition in Redshift
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:
1
2
3
4
5
6
SELECT
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,
FROM
products
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.
You may also like
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.