SQL Standard

SQL Rank Over

Ranking in SQL allows you to calculate the rank of each record within a partition within a result set.

The rank() will return a 1-based index for each record in an ordered partition in Standard SQL. Remember that the function will assign the same rank value to the partitions with similar values.

The number of previous rank values increments each consequent row rank value. If you wish to increment the rank value by 1, use the dense_rank() function.

Rank() Function Syntax

The syntax for the rank function is as shown below:

RANK() OVER (

[PARTITION BY expression, ]

ORDER BY expression (ASC | DESC) );

);

To illustrate how to use this function, consider the example below:

create table users(

id serial primary key,

first_name varchar(100),

last_name varchar(100),

state varchar(25),

active bool

);

insert into users(first_name, last_name, state, active) values (

'Mary', 'Smith', 'New York', TRUE);

insert into users(first_name, last_name, state, active) values (

'Linda', 'Williams', 'Colorado', FALSE);

insert into users(first_name, last_name, state, active) values (

'Taylor', 'Moore', 'Utah', TRUE);

insert into users(first_name, last_name, state, active) values (

'Susan', 'Wilson', 'Washington', TRUE);

insert into users(first_name, last_name, state, active) values (

'Mary', 'Smith', 'New York', TRUE);

insert into users(first_name, last_name, state, active) values (

'Taylor', 'Moore', 'Utah', TRUE);

The above queries create and insert sample data into the table.

To assign a rank to the records in the result set, we can use the rank() function as illustrated below.

select id, first_name, last_name, state, active,

rank () over (partition by active order by id) rank_value

from users;

In the above query, we partition the data by the active column. The column contains Boolean values. We then rank over each item in the partitions.

The resulting set is as shown:

Note that the result contains two partitions, one containing false values and the other containing true values.

In the “false’ partition, the function assigns the rank values. The same case for the “true” partition. Note that the function starts the rank value from 1 in a new partition.

Closing

This tutorial showed you how to perform row ranking by partitioning using the rank() function. Check the documentation for your database engine to learn more.

Thanks for reading!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list