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?

Table of Contents

  1. How does it work?

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:

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.

Older post

How to index data in Redshift

How to create an equivalent of an index in Redshift

Newer post

How to make an unconditional join in Redshift

LEFT OUTER JOIN ON 1=1 in Redshift

Are you looking for an experienced AI consultant? Do you need assistance with your RAG or Agentic Workflow?
Schedule a call, send me a message on LinkedIn. Schedule a call or send me a message on LinkedIn

>