Deviopath › PostgreSQL

Orders per Customer, Zeros Included

Medium · Joins

With a LEFT JOIN, a customer without orders still gets one row, with NULL order columns. COUNT(*) would count that row as 1, but COUNT(o.id) skips NULLs and gives 0.

Return name and order_count (orders of any status) for every customer, including customers with 0 orders. Sort by order_count descending, then name ascending.

Next: Who Is Your Manager?