N062-E2 Tier 5 · Expert · easy ecommerce · Brightlane

Return each customer's name and their order count, with the count reported as a missing value for customers who have no orders on record

Part of Choosing Between Subqueries, CTEs, and Joins in SQL

The problem

Scenario: Brightlane's CRM team needs a complete list of customers paired with each customer's order count, including customers who have placed no orders.

Task: Write a query to return each customer's name and their order count, with the count reported as a missing value for customers who have no orders on record.

Assumptions:

  • The result covers every customer.
  • A customer with no orders on record appears with order_count reported as a missing value (not 0).

Output:

  • One row per customer.
  • Columns in this order: customer_name, order_count.
Schema · ecommerce 5 tables
categories
id integer
name text
parent_id? integer
products
id integer
name text
category_id integer
price numeric
stock_qty integer
attributes? jsonb
order_items
id integer
order_id integer
product_id integer
quantity integer
unit_price numeric
customers
id integer
name text
email text
city? text
country text
created_at timestamptz
is_active boolean
orders
id integer
customer_id integer
ordered_at timestamptz
status text
total_amount numeric

Run previews · Check grades

Write a query, then run it to see results here.

Worked solution Try it yourself first
Solution query
SELECT
  c.name AS customer_name,
  order_counts.order_count
FROM
  customers c
  LEFT JOIN (
    SELECT
      customer_id,
      COUNT(*) AS order_count
    FROM
      orders
    GROUP BY
      customer_id
  ) AS order_counts ON order_counts.customer_id = c.id

The shape

A derived table pre-aggregates orders into one row per customer, and a LEFT JOIN from customers keeps every customer whether or not they appear in that aggregate. Customers with no orders end up matched to no row in the derived table, so order_count falls out as NULL on its own.

Clause by clause

  • FROM customers c is the driving side; every customer is preserved.
  • LEFT JOIN (SELECT customer_id, COUNT(*) AS order_count FROM orders GROUP BY customer_id) AS order_counts ON order_counts.customer_id = c.id aggregates orders down to one row per customer who has any, then joins that result back to customers on the customer id. The pre-aggregation is the load-bearing step; without it, the join would multiply each customer row by their order count.
  • SELECT c.name AS customer_name, order_counts.order_count returns the customer's name and the count from the derived table, which is NULL whenever the left join found no match.

Why this and not aggregating after the join

SELECT c.name, COUNT(o.id) FROM customers c LEFT JOIN orders o ON o.customer_id = c.id GROUP BY c.name also works, but it forces GROUP BY over every row of customers joined to every order. Pre-aggregating in a derived table aggregates first on the smaller side, then joins one row per customer to customers — cleaner intent and typically faster as orders grows. Either shape is correct.

The trap

The prompt requires NULL (not zero) for customers with no orders. Pre-aggregating preserves that automatically: the unmatched left-side rows pick up NULL from order_counts.order_count. Wrapping the column in COALESCE(..., 0) would change the contract and produce the wrong result here.

You practiced precomputing per-customer counts in a derived table before pairing it with the full customer list — preserving every customer while leaving no-order customers with a missing count.

How you actually get good at SQL

Reading explains SQL. Writing it, over and over with instant feedback, is what makes you fluent.

That's the whole SQLMaxx loop: 600+ real problems, instant AI feedback, mastery you can actually see, and spaced review that won't let you forget.

A stack of SQL practice problem cards, the top card showing an employees table.
615 problems · 66 concepts

Real problems. Not toy examples.

615 hand-built problems spanning all 66 concepts, from basic SELECTs to window functions, built on real schemas and real business questions, the kind you'll actually get asked on the job. Enough reps to make SQL automatic.

A retro computer showing a SQL query marked correct with a green checkmark.
Instant AI feedback

Write a query. Know if it's right in one second.

No copying an answer and hoping it clicked. The AI grader checks your real query against real data, catches exactly what's wrong, and explains the fix in plain English, like a senior analyst reading over your shoulder on every problem.

A circular mastery progress dial filling from blue to green, the SQLMaxx diamond at its center.
Mastery tracking

Stop guessing whether you actually know it.

SQLMaxx tracks every concept and shows you what you've mastered and what's still shaky. Your skills fill in one concept at a time, so 'I think I get joins' becomes something you can prove.

A SQL query editor circled by a blue return arrow with a clock, scheduled to come back for review.
Spaced review

Learn it once. Keep it for good.

Most of what you learn this week fades by next week. So when a concept comes due for review, SQLMaxx hands you a fresh problem to solve from a blank editor, not a flashcard to re-read. A research-backed spaced-repetition algorithm (FSRS) times each return for right before you'd forget, so your SQL is still there months later, when the interview or the job actually needs it.

Practice, feedback, mastery, review. That's the loop that turns reading into real skill.

Start free

No account, no credit card. Start solving in under a minute.