MySQL query to generate row index (rank) in SELECT statement?


To generate a row index, use ROW_NUMBER(). Let us first create a table −

mysql> create table DemoTable
(
   Name varchar(40)
);
Query OK, 0 rows affected (0.49 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Chris');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values('Chris');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Robert');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Robert');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Adam');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Adam');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values('Adam');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('Adam');
Query OK, 1 row affected (0.08 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------+
| Name   |
+--------+
| Chris  |
| Chris  |
| Chris  |
| Robert |
| Robert |
| Adam   |
| Adam   |
| Adam   |
| Adam   |
+--------+
9 rows in set (0.00 sec)

Following is the query to generate a row index in MySQL SELECT statement. Here, we have set rank for duplicate names −

mysql> select Name,
row_number() over (partition by Name) as `Rank`
from DemoTable;

This will produce the following output −

+--------+------+
| Name   | Rank |
+--------+------+
| Adam   | 1    |
| Adam   | 2    |
| Adam   | 3    |
| Adam   | 4    |
| Chris  | 1    |
| Chris  | 2    |
| Chris  | 3    |
| Robert | 1    |
| Robert | 2    |
+--------+------+
9 rows in set (0.00 sec)

Updated on: 06-Jul-2020

930 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements