// SQL snippet

Aggregate children into one row per parent

LEFT JOIN keeps parents without children; COUNT(child) counts 0 for them.

Main statement
All engines

The task

You want one row per customer with how many orders they placed and how much they spent, and customers who never ordered must still appear.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT c.id, c.name,
       COUNT(o.id) AS order_count,
       COALESCE(SUM(o.amount), 0) AS total_amount
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY total_amount DESC;

Cómo funciona

The LEFT JOIN keeps every customer even when no order matches, leaving the order columns NULL for those rows. COUNT(o.id) counts only non-NULL ids, so it correctly reports 0 rather than 1 for the childless rows; SUM returns NULL for them, which COALESCE turns into 0. This is the shape behind most list screens: parent attributes plus child aggregates in one pass. For the id list in the variant, SQL Server writes STRING_AGG(...) WITHIN GROUP (ORDER BY o.id), MySQL GROUP_CONCAT(o.id ORDER BY o.id) and Oracle LISTAGG(o.id, ',') WITHIN GROUP (ORDER BY o.id).

Variations

Plus a comma-joined list of order ids (PostgreSQL, SQLite 3.44+)

PostgreSQL SQLite
SELECT c.id, c.name,
       COUNT(o.id) AS order_count,
       STRING_AGG(CAST(o.id AS varchar), ',' ORDER BY o.id) AS order_ids
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY c.name;

Questions that come up

Why COUNT(o.id) and not COUNT(*)?

COUNT(*) counts rows, and a customer with no orders still contributes one row (all NULLs), which would read as 1 order. Counting the child column counts only real matches.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.