Brightlane's operations team maintains a daily pipeline log showing how many orders sit in each stage.
Write a query to return the count of orders in each status.
Assumptions:
- The
orderstable has one row per order with astatus. - Each
statusvalue present inordersshould appear once in the report.
Output:
- One row per status, with columns
statusandorder_count.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
WITH
status_counts AS (
SELECT
status,
COUNT(*) AS order_count
FROM
orders
GROUP BY
status
)
SELECT
status,
order_count
FROM
status_counts The shape
A WITH layer named status_counts computes the per-status COUNT(*) once, and the main query reads from it by name. The layer is the named subquery; the main query treats the name like a table.
Clause by clause
- The
WITHclause defines the named layer:
WITH status_counts AS (
SELECT status, COUNT(*) AS order_count
FROM orders
GROUP BY status
)Inside the parentheses, SELECT status, COUNT(*) AS order_count FROM orders GROUP BY status produces one row per distinct status with the count attached. That whole result set is what the name status_counts refers to.
SELECT status, order_count FROM status_countsis the main query. It reads from the named layer by name and returns its two columns straight through. The row for'delivered'carriesorder_count = 161;'shipped'carries17;'cancelled'and'pending'each carry11.
Why this and not a derived table in FROM
A derived table would compute the same per-status counts inside the FROM clause of the main query, no WITH involved. Both shapes return the same rows. The WITH version moves the aggregation above the main query and gives it a name, which means the main query reads top to bottom in the order the work happens. A derived table buries the aggregation inside the FROM clause of the same statement that consumes it. For a single-use named layer like this, the difference is organizational, not structural; WITH is the more readable spelling.
You practiced lifting a per-category breakdown into a named WITH layer that the main query reads from like a table.