Conditional Aggregation
What if you want several counts side by side, like all employees and high earners in each department? Put a CASE inside the aggregate.
SUM with CASE counts the rows that match a condition:
Each row adds 1 if it matches and 0 if it doesn't, so the SUM is the number of matches.
COUNT(CASE WHEN salary >= 120000 THEN 1 END) gives the same answer, because COUNT skips the NULLs that CASE returns for non-matches.
It works with any aggregate. Here's the payroll for people hired before 2019:
Turning rows into columns like this is also called a pivot. It's one of the most common patterns in analytics interviews.
Inside a GROUP BY, which expression counts employees earning at least 120,000?
Examples run on the employees sample database. Open any of them in the playground to experiment.