RANK is a window (analytic) function that assigns an integer rank to each row based on the ORDER BY clause of its OVER() window specification. The smallest ORDER BY value gets rank 1. If two or more rows tie, they receive the same rank and the next rank is incremented by the number of tied rows, leaving gaps (1,1,3 …). RANK works after the WHERE, GROUP BY, and HAVING phases but before the final ORDER BY of the entire query, meaning it sees the filtered, grouped result set.Because RANK is computed per window, you can optionally segment the data with PARTITION BY so each partition restarts at rank 1. Without PARTITION BY the entire result set is treated as one partition. RANK never changes underlying data; it only adds a derived column that can be used for reporting, pagination, or further filtering. Unlike ROW_NUMBER, RANK skips numbers on ties; unlike DENSE_RANK, it leaves gaps.RANK conforms to SQL:2003 and is widely supported, but exact syntactic details vary slightly by database (e.g., required ORDER BY direction, NULL ordering rules).
- PARTITION BY
(column_expression list) - Optional. Defines groups whose ranking restarts at 1.- ORDER BY
(column_expression list) - Required. Determines sort priority inside each partition.DENSE_RANK, ROW_NUMBER, NTILE, PARTITION BY, ORDER BY, WINDOW FUNCTIONS
SQL:2003 standard
ROW_NUMBER assigns unique sequential numbers even when rows tie; RANK assigns the same number to ties and skips the next numbers accordingly.
You cannot reference RANK directly in the same SELECT level's WHERE clause. Use a subquery or CTE to compute the rank first, then filter on it.
Ordering of NULLs follows the database's default or explicit NULLS FIRST/NULLS LAST specification. Ties involving NULLs receive the same rank.
In modern databases, window functions like RANK are optimized and usually outperform equivalent correlated subqueries for large datasets.