Regional order totals with zero-order regions
Return every region, its paid-order count, and paid revenue for January 2026—even when the region has no paid orders.
Output grain
One row per region.
Schema
CREATE TABLE regions (region_id INT PRIMARY KEY, name VARCHAR(40));
CREATE TABLE orders (
order_id INT PRIMARY KEY,
region_id INT REFERENCES regions(region_id),
status VARCHAR(20),
ordered_at TIMESTAMP,
total_amount DECIMAL(12,2)
);Think first
- Which table contains the full reporting population?
- Would a WHERE predicate remove the NULL-extended region rows?
Synthetic sample data
| region_id | name |
|---|---|
| 1 | North |
| 2 | South |
| 3 | West |
| order_id | region_id | status | ordered_at | total_amount |
|---|---|---|---|---|
| 101 | 1 | paid | 2026-01-08 | 120 |
| 102 | 1 | cancelled | 2026-01-09 | 60 |
| 103 | 2 | paid | 2026-01-12 | 80 |
| 104 | 2 | paid | 2026-02-02 | 40 |
Expected output
Validate values and row grain before opening the solution.
| region | paid_orders | paid_revenue |
|---|---|---|
| North | 1 | 120 |
| South | 1 | 80 |
| West | 0 | 0 |
Reasoning path
- 01
Preserve regions
Drive from regions and LEFT JOIN matching orders.
- 02
Filter matches
Put status and half-open date bounds in the ON clause.
- 03
Aggregate
COUNT the nullable order key and coalesce SUM for empty groups.
Reveal solution and explanationOPEN +CLOSE −
SELECT r.name AS region,
COUNT(o.order_id) AS paid_orders,
COALESCE(SUM(o.total_amount), 0) AS paid_revenue
FROM regions AS r
LEFT JOIN orders AS o
ON o.region_id = r.region_id
AND o.status = 'paid'
AND o.ordered_at >= TIMESTAMP '2026-01-01 00:00:00'
AND o.ordered_at < TIMESTAMP '2026-02-01 00:00:00'
GROUP BY r.region_id, r.name
ORDER BY r.name;How it works
- — The LEFT JOIN produces one NULL-extended row for West.
- — COUNT(o.order_id) ignores that NULL while SUM returns NULL, so COALESCE supplies zero.
Performance perspective
For a large orders table, index by the selective lookup path—often (region_id, status, ordered_at)—and verify with the real workload; low-cardinality status alone is rarely useful.
Edge cases
- — Refunded orders need an explicit business rule.
- — Use the reporting timezone when deriving month boundaries.