Xorthax can now assign a unique number to each row. But sometimes rows should share the same position.
“What if two rows are tied?”
That’s what RANK() handles.
RANK() assigns a position to each row—but allows ties.
RANK() OVER (
PARTITION BY column
ORDER BY column
)
This works by doing the following:
PARTITION BY defines the groupORDER BY defines how rows are ranked| CustomerID | Amount |
|---|---|
| A | 200 |
| A | 150 |
| A | 150 |
| A | 100 |
SELECT CustomerID, Amount,
RANK() OVER (
PARTITION BY CustomerID
ORDER BY Amount DESC
) AS RankValue
FROM Orders;
Result:
| CustomerID | Amount | RankValue |
|---|---|---|
| A | 200 | 1 |
| A | 150 | 2 |
| A | 150 | 2 |
| A | 100 | 4 |
Rows with the same value share the same rank.
ORDER BY Amount DESC ranks rows from highest to lowest.
RANK() assigns the same number to tied rows.
After a tie, the next rank skips ahead.
That’s why the ranks go: 1, 2, 2, 4.
⚠️ Important: If there are ties, RANK() will leave gaps in the sequence.
If you need rankings without gaps, you’ll use a different function next.
For each product, rank orders based on quantity from lowest to highest. Only include orders between 500 and 600.
| Column | Type |
|---|---|
| orderdetailid | bigint |
| orderid | bigint |
| productid | bigint |
| quantity | bigint |
| unitprice | double precision |
| currencyid | bigint |
| Column |
|---|
| orderid |
| productid |
| rank |
RANK() handles ties, but it leaves gaps in the ranking.
Next, you’ll learn how to rank rows without gaps.