The situation
The operations team reads a daily sheet with one row per store and one column per order status. The orders table has it the other way round: one row per order, with the status in a column.
The first version of the query left blanks in the sheet for stores that had no returns, and its columns did not add up to the number of orders.
Input tables
orders
One row per order.
| Column | Type | Description |
|---|---|---|
order_id |
BIGINT | Unique per order. |
store_id |
BIGINT | The store that took the order. |
status |
STRING | Normally DELIVERED, CANCELLED or RETURNED. Can be NULL, and can be something else. |
amount |
DECIMAL(10,2) | Order value in rupees. |
Requirement
Return one row per store.
delivered_orders,cancelled_ordersandreturned_orderscount the orders whose status is exactlyDELIVERED,CANCELLEDorRETURNED.other_orderscounts every other order: a NULL status, and any status that is not one of those three exact values (deliveredin lowercase is one of these).- The four counts of a store add up to its number of orders.
delivered_amountis the total amount of the store'sDELIVEREDorders.- A store with no orders of a kind shows 0 in that column, and 0.00 for the amount. Never NULL.
Expected output
One row per store.
| Column | Type | Description |
|---|---|---|
store_id |
BIGINT | |
delivered_orders |
BIGINT | |
cancelled_orders |
BIGINT | |
returned_orders |
BIGINT | |
other_orders |
BIGINT | NULL and unrecognised statuses. |
delivered_amount |
DECIMAL(12,2) | 0.00 if the store has no delivered orders. |
Solve it in the browser
This editor runs DuckDB inside your browser. Nothing is installed and nothing is sent
to a server. DuckDB's SQL is close to Spark SQL but not identical. The PIVOT clause behaves differently here: DuckDB fills a missing combination with 0, Spark leaves it NULL. Conditional counts give the same result in both.
The Colab notebook runs real Spark.
Your result appears here. Your draft is kept in this browser.
Explanation
Show explanationGives the answer away. Try the problem first.
The approach
Turning rows into columns is one aggregate per output column, each looking at only the rows it cares about:
COUNT(CASE WHEN status = 'DELIVERED' THEN 1 END) AS delivered_orders
The CASE returns 1 for a delivered order and NULL for anything else, because a
CASE with no ELSE returns NULL. COUNT(expression) counts the rows where the
expression is not NULL. So this counts the delivered orders, and when a store has
none it counts zero rows and returns 0. That is the whole trick, and it is why
COUNT is the right aggregate here and SUM is not.
Two columns need more care.
other_orders has to catch every status that is not one of the three, and a
missing status is one of them:
COUNT(CASE WHEN status IS NULL
OR status NOT IN ('DELIVERED', 'CANCELLED', 'RETURNED') THEN 1 END)
NULL NOT IN (...) is NULL, not true. Without the IS NULL the orders with no
status are in none of the four columns.
delivered_amount is a SUM, and SUM over no rows is NULL, so it is wrapped
in COALESCE(..., 0).
The table has 214 orders in 12 stores: 137 DELIVERED, 34 CANCELLED, 16
RETURNED, 13 PENDING, 10 with no status and 4 written as delivered.
Common wrong answers
SUM(CASE WHEN status = 'RETURNED' THEN 1 END). Fine for a store that has
returns. For a store that has none, every CASE result is NULL and SUM of nothing
but NULLs is NULL. Six of the 12 stores get a NULL somewhere: four have no returns,
two have no cancellations and one has no deliveries. These are the blanks in the
sheet. SUM(CASE WHEN ... THEN 1 ELSE 0 END) fixes it; COUNT without the ELSE
is shorter.
COUNT(CASE WHEN status = 'DELIVERED' THEN 1 ELSE 0 END). The opposite mistake.
COUNT counts 0 just as happily as 1, so this counts every order. It is wrong for
11 of the 12 stores, and right for store 12 only because all of its orders were
delivered.
status NOT IN (...) without IS NULL. other_orders is too low for 8 stores,
the ones with at least one order that has no status. The four columns no longer add
up to the number of orders, which is the second complaint in the story.
No COALESCE on the amount. Store 11 has no delivered orders and shows NULL
instead of 0.00.
UPPER(status) = 'DELIVERED'. Counts the four delivered rows as delivered.
The requirement says exactly DELIVERED. Whether lowercase is the same status is a
question for whoever owns the data; quietly normalising it in a report hides the
data entry problem. Wrong for 4 stores.
The PIVOT clause.
SELECT * FROM (SELECT store_id, status FROM orders)
PIVOT (COUNT(*) FOR status IN ('DELIVERED', 'CANCELLED', 'RETURNED'))
In Spark this returns NULL, not 0, where a store has no orders of a kind, even
though the aggregate is a count. A missing combination has no group at all, so
there is nothing to count. It also has no column for the other statuses:
PENDING, delivered and whatever turns up next would each need their own entry
in the list. PIVOT is useful when the list of values is long; for three known
values the conditional counts are clearer and safer.
Other ways to write it
All of these give the same result as the reference solution:
COUNT_IF(status = 'RETURNED')COUNT(*) FILTER (WHERE status = 'RETURNED')other_ordersasCOUNT(*)minus the count of the three known statuses. This cannot miss a row, whatever turns up in the column.
Edge cases in the data
| Case | Where | What it catches |
|---|---|---|
| Store with no delivered orders | store 11 | SUM without ELSE; amount without COALESCE. |
| Store with only delivered orders | store 12 | NULLs in three count columns at once; makes COUNT(... ELSE 0) look right. |
| Stores with no returns or no cancellations | 1, 5, 7, 8, 12 | The same, in ordinary stores. |
| Orders with no status | 10 orders in 8 stores | NOT IN without IS NULL. |
PENDING |
13 orders | A status the report does not know must land in other_orders. |
delivered in lowercase |
4 orders in 4 stores | Case-insensitive matching. |