CASE and Conditional Aggregation: Rows to Columns

SQL Interview Problems: 12 Classic Questions Solved · Counting, Traps and Speed · 6 min read · Updated

Counting with CASE

  1. The query reads each row of the table once.
  2. CASE WHEN tests a condition on the row, for example salary at least 100000.
  3. It returns 1 when the condition is true and 0 when it is not.
  4. SUM adds the ones, which is the same as counting the matching rows.
  5. Several CASE columns give several counts in one result row.

A report often needs several numbers in one row: how many people are paid 100000 or more, how many are paid less, and how many have no salary recorded yet. Or sales by employee with one column per month. You could write one query for each number, but there is a better way. CASE inside an aggregate function counts only what matches a condition. It is called conditional aggregation, and it is also how you build a pivot table in a database that has no PIVOT keyword.

CASE is an if-else for one value

CASE WHEN condition THEN result ... ELSE other END returns a value for each row. The conditions are checked from top to bottom, and the first one that is true wins. Use it to label rows.

SELECT name, salary,
       CASE
         WHEN salary IS NULL THEN 'unknown'
         WHEN salary >= 120000 THEN 'senior band'
         WHEN salary >= 80000  THEN 'mid band'
         ELSE 'entry band'
       END AS band
FROM employees
ORDER BY salary IS NULL, salary DESC, name;
name        | salary | band
Meera Joshi | 150000 | senior band
Nia Okoye   | 130000 | senior band
Arjun Rao   | 120000 | senior band
Sara Khan   | 120000 | senior band
Omar Ali    | 110000 | mid band
Dev Patel   | 100000 | mid band
Liam Brown  | 95000  | mid band
Ravi Menon  | 90000  | mid band
Chloe Wu    | 72000  | entry band
Priya Nair  | 70000  | entry band
Tom Hill    | 70000  | entry band
Zoe Park    | 65000  | entry band
Ella Stone  | 55000  | entry band
Jack Reed   | NULL   | unknown

The order of the conditions matters. A salary of 150000 is also at least 80000, but it gets senior band because that test comes first. The NULL test must also come first, because a comparison with NULL is never true and a missing salary would fall through to entry band. The ORDER BY salary IS NULL trick puts rows with a NULL last in SQLite, MySQL and PostgreSQL, because salary IS NULL is 0 for normal rows and 1 for missing ones. SQL Server needs ORDER BY CASE WHEN salary IS NULL THEN 1 ELSE 0 END for the same effect.

Counting with conditions

Inside SUM, a CASE that returns 1 for matching rows and 0 for the rest simply counts the matches. All the counts are calculated in one pass over the table.

SELECT SUM(CASE WHEN salary >= 100000 THEN 1 ELSE 0 END) AS paid_100k_or_more,
       SUM(CASE WHEN salary <  100000 THEN 1 ELSE 0 END) AS paid_less,
       COUNT(*) - COUNT(salary) AS unknown
FROM employees;
paid_100k_or_more | paid_less | unknown
6                 | 7         | 1

Six people are paid 100000 or more, seven are paid less, and one salary is unknown. The three numbers add up to 14, our number of employees. That adding-up check is a good habit. If the numbers do not add up, you have lost a row, usually to a NULL.

COUNT(*) - COUNT(salary) is a short way to count the NULL values, because COUNT(salary) counts only the rows that have a salary.

Conditions per group

Combine it with GROUP BY to get a number per department: how many people joined the company since the start of 2022?

SELECT d.name,
       COUNT(*) AS total,
       SUM(CASE WHEN e.hired >= '2022-01-01' THEN 1 ELSE 0 END) AS hired_since_2022
FROM employees e
JOIN departments d ON d.id = e.dept_id
GROUP BY d.id
ORDER BY d.name;
name        | total | hired_since_2022
Engineering | 5     | 2
Finance     | 3     | 2
HR          | 2     | 1
Sales       | 4     | 2

Each department shows its total headcount and how many of them were hired from 2022 onwards. If you only wrote WHERE hired >= '2022-01-01', the total column would disappear, because WHERE removes the rows before they are counted. Conditional aggregation keeps both numbers side by side.

Rows to columns: a pivot

Pivoting means turning the values of one column into column headings. We want one row per employee and one column per month. For each month column, add up the amount only when the sale falls in that month.

SELECT employee_id,
       SUM(CASE WHEN strftime('%m', sale_date) = '01' THEN amount ELSE 0 END) AS jan,
       SUM(CASE WHEN strftime('%m', sale_date) = '02' THEN amount ELSE 0 END) AS feb,
       SUM(CASE WHEN strftime('%m', sale_date) = '03' THEN amount ELSE 0 END) AS mar,
       SUM(CASE WHEN strftime('%m', sale_date) = '04' THEN amount ELSE 0 END) AS apr,
       SUM(amount) AS total
FROM sales
GROUP BY employee_id
ORDER BY employee_id;
employee_id | jan  | feb  | mar  | apr  | total
6           | 1200 | 1900 | 2000 | 1800 | 6900
7           | 800  | 900  | 1400 | 500  | 3600
8           | 500  | 700  | 600  | 1000 | 2800

Employee 6 sold 1200 in January, 1900 in February, 2000 in March and 1800 in April, 6900 in total. The ELSE 0 matters. Without it, a month with no sales would show NULL instead of 0, which is often what you want to avoid in a report. Some databases have a PIVOT keyword, but the CASE way works everywhere and is what interviewers expect.

Common mistakes

  • Putting the conditions in the wrong order in a CASE.
  • Leaving out ELSE and getting NULL where you wanted 0.
  • Using WHERE for a condition that should only affect one column of the result.
  • Forgetting that CASE returns one type. Mixing text and numbers in the results can give errors in some databases.

Your task

  1. Count the employees in each department who earn more than 100000, next to the total of the department.
  2. Show for each employee how many of their sales were 1000 or more, and how many were less.
  3. Add a total row of the monthly figures using a second query and UNION ALL. (Look up how it works if you have not used it.)
  4. Change the salary label query so that the bands are: under 70000, 70000 to 99999, and 100000 or more.

How to check it worked

  • The three salary counts add up to 14.
  • Employee 7's March column shows 1400 and April shows 500.
  • Engineering shows 5 people in total and 2 hired since 2022.

Frequently asked questions

What is conditional aggregation?

It is using CASE inside an aggregate function such as SUM or COUNT so that only rows matching a condition are counted or added.

Can I use FILTER instead of CASE?

PostgreSQL and recent SQLite support SUM(x) FILTER (WHERE condition), which is shorter. MySQL and SQL Server do not, so CASE is the portable choice.

How do I pivot when the columns are not known in advance?

Plain SQL cannot. You generate the query text in code or use a reporting tool that creates the columns for you.