Brightlane's product team is preparing a catalogue sorted by price for a buyer presentation.
Write a query to return each product's name and price, sorted from the least expensive to the most expensive.
Assumptions:
- The
productstable contains every product in Brightlane's catalogue. - When two products share the same price, the product with the lower
idshould appear first.
Output:
- One row per product, with columns
nameandprice, sorted bypriceascending, then byidascending.
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
name,
price
FROM
products
ORDER BY
price,
id The shape
A two-key ORDER BY — price first, then id as a tiebreaker — turns the catalogue into a deterministic least-to-most-expensive list, even when two products share a price.
Clause by clause
SELECT name, pricepulls the two columns the buyer presentation needs. Nothing else fromproductsappears in the output, but every product is still considered for sorting.FROM productsreads the catalogue. Without anyWHERE, every row in the table is in play.ORDER BY price, idsorts bypriceascending — ascending is the default, so noASCis needed — and usesidto break ties. Two products at12.99(HDMI Cable 2mandPicture Frame 8x10) come back in the order theiridvalues prescribe, so the result is reproducible run after run.
Why this and not ORDER BY price on its own
Without the id tiebreaker, PostgreSQL is free to return the two 12.99 rows in either order, and that order can change between runs as the planner picks different strategies. The query is still correct in the sense that the prices are sorted, but the row sequence inside any group of equal prices is up to the engine. The second sort key locks the order down so the presentation looks the same every time it's exported.
You practiced sorting on a primary key with a secondary tie-breaker. Adding a stable second sort key is the recurring fix for any list whose primary sort can produce ties — it makes the output order deterministic instead of arbitrary.