ROW_NUMBER
Description
The ROW_NUMBER()
function is used to calculate the row number of the current row within its partition, starting from 1, and ordered by the specified ORDER BY
clause. This function is very useful when processing data, especially when you need to assign a unique sequence number to each row in the result set.
Syntax
Parameter Description
partition_expression
: An expression used to define partitions, there can be multiple, used to divide the result set into multiple partitions.sort_expression
: An expression used to specify sorting, it can be a column name or an expression, used to sort rows within each partition.ASC
|DESC
: Optional parameters used to specify the sorting direction, default isASC
.
Return Result
- The return value type is
bigint
. - The returned row numbers are continuous and non-repetitive.
Usage Example
- Basic usage:
- Using Partitions:
- Multi-column Sorting:
Notes
- The
ROW_NUMBER()
function is independent for each partition, meaning each partition will have its own sequence of row numbers. - When using the
ROW_NUMBER()
function, ensure that the columns in theORDER BY
clause are unique to avoid generating non-continuous row numbers. - When the columns in the
ORDER BY
clause have the same values, theROW_NUMBER()
function will, by default, generate non-continuous row numbers. If continuous row numbers are needed, consider using theDENSE_RANK()
function.