N031-M3 Tier 3 · Intermediate · medium ecommerce · Brightlane

Return each qualifying customer's ID and their count of high-value orders

Part of Chained CTEs in SQL

The problem

Brightlane's finance team wants to identify customers who have placed high-value orders, along with how many such orders each customer has on record.

Write a query to return each qualifying customer's ID and their count of high-value orders.

Assumptions:

  • A high-value order has total_amount greater than $500.
  • A customer's high-value-order count is the number of high-value orders linked to that customer_id.
  • Only customers with at least one high-value order should appear.

Output:

  • One row per qualifying customer, with columns customer_id and big_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
WITH
  big_orders AS (
    SELECT
      customer_id,
      total_amount
    FROM
      orders
    WHERE
      total_amount > 500
  ),
  customer_counts AS (
    SELECT
      customer_id,
      COUNT(*) AS big_order_count
    FROM
      big_orders
    GROUP BY
      customer_id
  )
SELECT
  customer_id,
  big_order_count
FROM
  customer_counts

The shape

Restrict first, then aggregate. The first CTE keeps only the high-value orders, and the second counts those qualifying rows per customer. Because the count runs over the already-filtered set, every counted row is by definition a big order and no row needs to be discounted at aggregation time.

Clause by clause

The first CTE drops every order below the threshold:

WITH big_orders AS (
  SELECT customer_id, total_amount
  FROM orders
  WHERE total_amount > 500
)

WHERE total_amount > 500 filters the orders before any grouping happens. The SELECT list carries customer_id forward because the next layer needs it as the grouping key, and total_amount could be dropped here but is harmless to keep.

The second CTE groups the qualifying orders by customer:

customer_counts AS (
  SELECT customer_id, COUNT(*) AS big_order_count
  FROM big_orders
  GROUP BY customer_id
)

FROM big_orders reads only the orders that survived the filter. GROUP BY customer_id produces one row per customer, and COUNT(*) counts the high-value orders in each group. Customers with zero big orders never appear in big_orders and therefore never appear in this layer either, which is the "at least one" requirement satisfied implicitly.

  • SELECT customer_id, big_order_count FROM customer_counts returns the final per-customer counts.

Why restrict in the first CTE instead of restricting after the aggregation

Moving the threshold up front is what makes "at least one high-value order" automatic. A customer with no qualifying orders contributes no rows to big_orders and therefore no row to customer_counts. If the filter were skipped and the count were computed first across all orders, the threshold would have to come back as a separate condition on the count, and the count itself would be "all orders" rather than "high-value orders." The order of operations changes what is being counted, not just how the answer is filtered. Restricting first is what makes the count a count of high-value orders.

You practiced layering two WITH stages — pre-restrict the source records in the first stage, then compute a per-customer count over only the qualifying records in the second.

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.