Ties, RANK and PARTITION BY
When ties should share a place, use RANK() or DENSE_RANK() instead of ROW_NUMBER():
| stock_qty | ROW_NUMBER() | RANK() | DENSE_RANK() |
|---|---|---|---|
| 500 | 1 | 1 | 1 |
| 500 | 2 | 1 | 1 |
| 420 | 3 | 3 | 2 |
RANK()is like a sports table: two joint-firsts, then third.DENSE_RANK()leaves no gaps: two joint-firsts, then second.
PARTITION BY restarts the numbering for each group, like a separate league table per category:
SELECT name, category, list_price,
RANK() OVER (PARTITION BY category ORDER BY list_price DESC) AS rank_in_category
FROM productsEvery product keeps its own row; the rank just counts within its category.