Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing
Back
  1. Home
  2. Interview prep
  3. SUM(CASE WHEN...) and conditional aggregation

SQL · Aggregations & Grouping

SUM(CASE WHEN...) and conditional aggregation

Mediumsql-13
conditional aggregationcase whensum

Question

How does SUM(CASE WHEN ...) work for conditional aggregation?

Solution

SUM(CASE WHEN...) is a common form of conditional aggregation.

Example:

SELECT
    SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END)
FROM orders;

This counts completed orders.

You can also calculate amounts:

SUM(
    CASE
        WHEN status = 'completed'
        THEN amount
        ELSE 0
    END
)

Same idea either way: aggregate only the rows that match a condition.

In short:

> Conditional aggregation means applying an aggregate function only to rows that satisfy a condition.

🎯 Put this concept into practice

Solidify this answer with real hands-on interview drills in the browser studio.

Open related drill →
PreviousNext