sqlcmd.net validated sql reference
advanced aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Aggregate Rows Conditionally With CASE Inside An Aggregate

Use `CASE WHEN` inside `SUM` or `COUNT` to produce multiple metrics from a single pass over grouped data.

Docker-validated Not currently validation-green

Count shipped orders and sum pending amounts per customer

Three separate metrics are computed in one GROUP BY pass. SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END) counts only shipped rows. SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END) totals amounts only for pending rows. Bob has two shipped orders and zero pending value; Carol has one pending order worth 75.

Rows loaded before the example query runs.
Setup
CREATE TABLE orders (
  id INT,
  customer VARCHAR(50),
  status VARCHAR(20),
  amount INT
);

INSERT INTO
  orders (id, customer, status, amount)
VALUES
  (1, 'Alice', 'shipped', 100),
  (2, 'Alice', 'pending', 50),
  (3, 'Bob', 'shipped', 200),
  (4, 'Bob', 'shipped', 150),
  (5, 'Carol', 'pending', 75);
Shared across supported engines.
SQL
SELECT
  customer,
  COUNT(*) AS total_orders,
  SUM(
    CASE
      WHEN status = 'shipped' THEN 1
      ELSE 0
    END
  ) AS shipped,
  SUM(
    CASE
      WHEN status = 'pending' THEN amount
      ELSE 0
    END
  ) AS pending_value
FROM
  orders
GROUP BY
  customer
ORDER BY
  customer;
Returned rows for the shared example.
customertotal_ordersshippedpending_value
Alice2150
Bob220
Carol1075

Output is identical across all engines.

Where this command helps.

  • counting how many rows per group match different status values in one query
  • summing amounts separately for each category without multiple subqueries

What the command is doing.

Conditional aggregation embeds a CASE WHEN expression inside an aggregate function like SUM or COUNT. Each row contributes a value only when its condition is true — otherwise it contributes zero or null. This lets you pivot status categories, compute split totals, or count matching rows without multiple subqueries.