Brightlane's product catalog ranks items by price from highest to lowest.
Write a query to return the ID, name, and price of every product, plus the product's rank by price in descending order.
Assumptions:
- The
productstable has one row per product with anid, aname, and aprice. - Rank
1goes to the highest-priced product, with rank values increasing aspricedecreases. - Products with the same
pricereceive the same rank. The next rank value after a tie is adjusted upward by the number of tied products, so rank values may have gaps.
Output:
- One row per product, with columns
id,name,price, andprice_rank.
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,
RANK() OVER (
ORDER BY
price DESC
) AS price_rank
FROM
products The shape
RANK() OVER (ORDER BY price DESC) assigns the same rank to products that tie on price and then skips ahead so the next rank reflects the number of rows that came before it. A price list with two items tied at the top would read 1, 1, 3, ..., not 1, 1, 2, ....
Clause by clause
SELECT id, name, price, RANK() OVER (ORDER BY price DESC) AS price_rankreturns each product's ID, name, price, and its competitive rank. The window'sORDER BY price DESCdefines the descending price order inside which the rank is computed; withoutPARTITION BY, the whole catalog is one window.FROM productsreads the product catalog.
Why RANK and not ROW_NUMBER
ROW_NUMBER would give each tied product a different number even though their prices are identical, which understates the tie. RANK carries the tie through to the output and the gap after the tie communicates how many products sat at the higher price. The gap is informative: a product showing price_rank = 5 means four products are strictly more expensive than it, regardless of whether some of those four are tied with each other.
The trap
The gap after a tie is not a bug. A reader expecting consecutive integers 1, 2, 3, ... will see 1, 1, 3, ... and assume rank 2 is missing. It is not missing; it is the tie. If the consumer wants consecutive integers across ties, DENSE_RANK is the function for that. The two functions answer different questions about ties, and the choice between them is load-bearing.
You practiced RANK() OVER (ORDER BY ...) — tied rows share the same rank; the sequence skips ahead by the number of tied rows, leaving gaps.