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.

SqlData Fetching

Code

snippet
-- 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

FAQ

What are the relations in play here?
`categories`, `orders` — joined via 2 JOIN clauses.