N061-H3 Tier 5 · Expert · hard ecommerce · Brightlane

Return each qualifying `product_id` and its `price`

Part of Query Structure Patterns for Performance in SQL

The problem

Scenario: Brightlane's pricing team is auditing products that are priced above the average for their own category.

Task: Write a query to return each qualifying product_id and its price.

Assumptions:

  • The products table holds one row per product, with id identifying it, category_id recording its category, and price storing its current price.
  • The category average price for a product is the average price across every product sharing the same category_id.
  • The result covers only products whose price is strictly greater than the category average price for their own category.

Output:

  • One row per qualifying product.
  • Columns in this order: product_id, price.
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
  p.id AS product_id,
  p.price
FROM
  products p
  JOIN (
    SELECT
      category_id,
      AVG(price) AS avg_price
    FROM
      products
    GROUP BY
      category_id
  ) AS cat_avg ON cat_avg.category_id = p.category_id
WHERE
  p.price > cat_avg.avg_price

The shape

Every product has to be compared against a value that itself depends on the whole category. A derived table computes the per-category average once per category, the main query joins each product to its category's row, and the WHERE then compares the product's price against the category benchmark sitting on the same row.

Clause by clause

  • The derived table:
SELECT category_id, AVG(price) AS avg_price
FROM products
GROUP BY category_id

One row per category, with the category's average price already computed across every product in that category. - SELECT p.id AS product_id, p.price returns the product's identifier and its own price — the category average is used for the comparison but is not in the output. - FROM products p JOIN (...) AS cat_avg ON cat_avg.category_id = p.category_id attaches each product to its category's benchmark row. Every product belongs to exactly one category, so the join produces exactly one row per product. - WHERE p.price > cat_avg.avg_price keeps only the products whose price strictly exceeds their category's average.

Why this and not a correlated subquery in WHERE

The same logic can be written as WHERE p.price > (SELECT AVG(price) FROM products p2 WHERE p2.category_id = p.category_id). The result is identical. The cost is not: the correlated form re-runs the subquery once per outer row, recomputing the same per-category average for every product in that category. The derived-table form computes each category's average exactly once and the join broadcasts it. On a large catalog that is the difference between scanning the table once per category and scanning it once per product.

The trap

The category average includes the product being compared against it. A product priced at the category mean is not above its category average and is correctly excluded by the strict >. But the average itself is pulled toward the product's own price by including it — on a category with only two products, each product's price contributes half the average, so the cheaper product can only be "below" by exactly the gap between the two prices. The benchmark is not "the average of the other products in the category"; it is "the average of every product in the category, including this one." The prompt asks for the latter, and that is what this query computes. If the analyst wanted the former, the derived table would need to exclude each product from its own group, which is a different shape entirely.

You practiced precomputing per-category averages in a derived table, then reattaching each product to its category benchmark for comparison — a shape that runs the average computation once per category rather than once per product.

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.