What is ROW_NUMBER() in MySQL?

MySQLMySQLi Database

Row_NUMBER() included from MySQL version 8.0. It is a type of window function. This can be used to assign a sequence number for rows. To understand, create a table with the help of CREATE pcommand −

Creating a table

mysql> CREATE table rowNumberDemo
-> (
-> FirstName varchar(100)
-> );
Query OK, 0 rows affected (0.92 sec)

Inserting records

mysql> INSERT into rowNumberDemo values('john');
Query OK, 1 row affected (0.17 sec)

mysql> INSERT into rowNumberDemo values('john');
Query OK, 1 row affected (0.29 sec)

mysql> INSERT into rowNumberDemo values('Bob');
Query OK, 1 row affected (0.13 sec)

mysql> INSERT into rowNumberDemo values('Smith');
Query OK, 1 row affected (0.17 sec)

We can display all the records with the help of SELECT statement −

mysql> SELECT * from rowNumberDemo;

The following is the output −

+-----------+
| FirstName |
+-----------+
| john      |
| john      |
| Bob       |
| Smith     |
+-----------+
4 rows in set (0.00 sec)

Now, we can use the row_number() to assign a incrementing value for every record −

mysql> SELECT row_number() over ( order by firstName) RowNumberSqeuence,FirstName from rowNumberDemo
-> order by FirstName;

The following is the output −

+-------------------+-----------+
| RowNumberSqeuence | FirstName |
+-------------------+-----------+
| 1                 | Bob       |
| 2                 | john      |
| 3                 | john      |
| 4                 | Smith     |
+-------------------+-----------+
4 rows in set (0.00 sec)

Look at the output, we have assigned a number to every record with the help of row_number().

raja
Published on 22-Oct-2018 09:10:24
Advertisements