Brightlane's product manager wants the price range for each product's category alongside the individual product price.
Write a query to return the ID, category ID, and price of every product, plus both the minimum and maximum prices across the product's category on each row.
Assumptions:
- The
productstable has one row per product with anid, acategory_id, and aprice. - A category's minimum price is the lowest
priceacross every product in thatcategory_id. A category's maximum price is the highestpriceacross every product in thatcategory_id. Both values should appear on every row that shares acategory_id.
Output:
- One row per product, with columns
id,category_id,price,cat_min_price, andcat_max_price.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
id,
category_id,
price,
MIN(price) OVER (
PARTITION BY
category_id
) AS cat_min_price,
MAX(price) OVER (
PARTITION BY
category_id
) AS cat_max_price
FROM
products The shape
Two window functions ride alongside each other, both partitioned by category_id. MIN(price) OVER (PARTITION BY category_id) writes the category's lowest price onto every row in the category, and MAX(price) OVER (PARTITION BY category_id) writes the category's highest price onto the same rows. Every product keeps its own price and gets the category's range as two additional columns.
Clause by clause
SELECT id, category_id, pricereturns each product's identifier, category, and individual price.- The two window columns are:
MIN(price) OVER (PARTITION BY category_id) AS cat_min_price,
MAX(price) OVER (PARTITION BY category_id) AS cat_max_priceEach OVER (PARTITION BY category_id) defines its own window: rows are grouped by category_id, the function runs independently inside each group, and the per-group result is replicated onto every row of that group. MIN and MAX see the same partitioning, so all rows in a given category share both the same cat_min_price and the same cat_max_price.
FROM productsreads the catalog. The product manager wants the range next to each individual product, so every row stays in.
Why two windows and not one
A single window function returns one column. The brief needs both ends of the range, the minimum and the maximum, alongside each product's individual price. Two parallel windows are how a window query produces more than one per-group aggregate: each window function names its own column in the SELECT list and pulls its own value from the same partition.
You practiced two parallel OVER (PARTITION BY ...) windows — MIN and MAX partitioned by the same column produce the partition's range as two columns, side by side with the per-record value.