Brightlane's catalog analyst tracks how the lowest and highest observed prices change as products are reviewed in sequence by id.
Write a query to return the ID, name, and price of every product, plus the running minimum and running maximum price observed from the first product through that product in order of id.
Assumptions:
- The
productstable has one row per product with anid, aname, and aprice. - Products are reviewed in ascending
idorder. The running minimum at each row is the lowestpriceseen across every product whoseidis less than or equal to that row'sid. The running maximum is the highestpriceseen across the same set.
Output:
- One row per product, with columns
id,name,price,running_min, andrunning_max.
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,
name,
price,
MIN(price) OVER (
ORDER BY
id
) AS running_min,
MAX(price) OVER (
ORDER BY
id
) AS running_max
FROM
products The shape
MIN(price) OVER (ORDER BY id) and MAX(price) OVER (ORDER BY id) track the lowest and highest price observed from the first product through the current row. Both values update only when a new extreme arrives. The running minimum never increases; the running maximum never decreases. As the catalog is reviewed in id order, the two columns hold the running floor and ceiling of the prices seen so far.
Clause by clause
SELECT id, name, pricereturns each product's identifier, name, and price. The two running extremes are attached.MIN(price) OVER (ORDER BY id) AS running_minreturns the smallestpriceacross every row from the start of the table through the current one. On the first row,running_minequals that row's ownprice,999. On the second row,running_minstays at999because the second price,1199, is higher. The value drops only when a lower price arrives.MAX(price) OVER (ORDER BY id) AS running_maxreturns the largestpriceacross the same accumulating set. On the first row, it equals999. On the second row, it rises to1199because that exceeds the previous maximum. The value rises only when a higher price arrives.FROM productsreads every product. Both window expressions accumulate over the same growing row set, defined byORDER BY idinsideOVER.
Why running MIN and MAX and not a grouped MIN and MAX
A grouped MIN(price) and MAX(price) would return one number each across the whole catalog, with no row-level detail. The catalog analyst needs to see, at each product, the floor and ceiling reached up to that point in the review sequence. That's a per-row question, and the windowed form answers it without collapsing the rows.
You practiced running MIN and MAX over an ordered window — both values update only as smaller or larger values enter the cumulative set; otherwise they hold steady.