Updated on 2026-11-06 GMT+08:00

rank

Function

The rank function is used to calculate the rank of a value within a set of values. If there are ties, the rank function leaves gaps in the ranking sequence.

Usage Restrictions

The usage restrictions for window functions are as follows:

  • Window functions can only appear in SELECT statements.
  • Window functions cannot be nested with other window functions or aggregate functions.
  • Window functions cannot be used together with aggregate functions at the same level.

Syntax

rank() over ([partition_clause] [orderby_clause])

Parameters

Parameter

Mandatory

Description

partition_clause

No

Specifies the partition. Rows with the same value in the partition column are considered to be within the same window.

orderby_clause

No

Specifies how data is sorted within a window.

Return Values

Returns a value of type INT.

Examples

To facilitate understanding of the function's usage, source data is provided along with function-related examples. Create the logs table and add data with the following example command:

CREATE TABLE logs (
cookieid string,
createtime string,
pv INT
) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' 
stored as textfile;

Add data as follows:

cookie1 2015-04-10 1
cookie1 2015-04-11 5
cookie1 2015-04-12 7
cookie1 2015-04-13 3
cookie1 2015-04-14 2
cookie1 2015-04-15 4
cookie1 2015-04-16 4
cookie2 2015-04-10 2
cookie2 2015-04-11 3
cookie2 2015-04-12 5
cookie2 2015-04-13 6
cookie2 2015-04-14 3
cookie2 2015-04-15 9
cookie2 2015-04-16 7

Example: Group all records by cookieid, sort by pv in descending order, and return the sequence number for each row within the group. Example command:

select cookieid, createtime, pv,
       rank() over(partition by cookieid order by pv desc) as rank
from logs
where cookieid = 'cookie1';
-- Result:
cookie1 2015-04-12 7 1
cookie1 2015-04-11 5 2
cookie1 2015-04-16 4 3 (tied for third)
cookie1 2015-04-15 4 3
cookie1 2015-04-13 3 5 (skips 4, starts from 5)
cookie1 2015-04-14 2 6
cookie1 2015-04-10 1 7