Zero Count Categories With Left Join
A LEFT JOIN before GROUP BY keeps categories with no matching rows, and COUNT over the joined column reports 0 — filters must move into ON or they vanish.
Code
-- INNER JOIN 会把没订单的类别整行丢掉,报表上"0 个订单"的类别凭空消失;
-- 先 LEFT JOIN 再分组,没有匹配行的组 COUNT(订单列) 返回 0
SELECT
c.category_id,
c.name,
COUNT(o.order_id) AS order_count,
COALESCE(SUM(o.total_cents), 0) AS revenue_cents
FROM categories c
LEFT JOIN orders o ON o.category_id = c.category_id
GROUP BY c.category_id, c.name
ORDER BY order_count ASC, c.name;
-- 注意:把时间过滤写进 WHERE 会把补空行也滤掉(join 退回 inner),
-- 想保留 0 计数,条件必须放进 ON
SELECT c.category_id, COUNT(o.order_id) AS recent_orders
FROM categories c
LEFT JOIN orders o ON o.category_id = c.category_id
AND o.created_at >= TIMESTAMP '2026-11-01'
GROUP BY c.category_id
ORDER BY c.category_id;Inside the snippet
A single SELECT does the work here, LEFT JOINing categories to orders and counting per category.
Concretely, the SQL combines: 2 JOINs combining rows across tables; COUNT, SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.
What to watch for
- 2 joins multiply the intermediate row count; confirm the join keys are indexed before pointing this at production-sized tables.
Putting it to use
The categories table is the working surface here.
Core lines
SELECT
c.category_id,
c.name,
COUNT(o.order_id) AS order_count,
COALESCE(SUM(o.total_cents), 0) AS revenue_cents
FROM categories c
LEFT JOIN orders o ON o.category_id = c.category_id
GROUP BY c.category_id, c.name
ORDER BY order_count ASC, c.name;
SELECT c.category_id, COUNT(o.order_id) AS recent_orders
FROM categories c
LEFT JOIN orders o ON o.category_id = c.category_id
AND o.created_at >= TIMESTAMP '2026-11-01'
GROUP BY c.category_id
ORDER BY c.category_id;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What are the relations in play here?
- `categories`, `orders` — joined via 2 JOIN clauses.
Report a problem with this exampleOpens a pre-filled issue on GitHub.