SQL Functions and Aggregation/Conditional aggregation with CASE

Compute multiple categorized totals in one query.

Section: Advanced Aggregation

Conditional aggregation with CASE

sql
sql
SELECT
  COUNT(*) AS total_orders,
  SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid_orders,
  SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END) AS refunded_orders
FROM orders;
Explanation

CASE inside aggregates is a staple reporting pattern.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Advanced Aggregation
Aggregate by date
Roll up metrics by calendar day.
OpenIn sheetsqlsame section
Count distinct values
Count unique entries in a column.
OpenIn sheetsqlsame section
Use CASE expression
Return different values based on conditions.
OpenIn sheetsql1 tag match
Concatenate strings
Join multiple strings into one value.
Get current date and timestamp
Return the current date and current timestamp.
Change case
Convert strings to uppercase or lowercase.