JIYIK CN >

Current Location:Home > Learning > DATABASE > MySQL >

How to use the Row_Number() function in MySQL

Author:JIYIK Last Updated:2025/04/11 Views:

In this tutorial, we will explain how to use the VALUES function in MySQL ROW_NUMBER(). This is a sorting method that assigns consecutive numbers within a partition starting from 1. It is important to note that no two rows within a partition have the same number.

We will also see how PARTITION BYAND ORDER BYaffects MySQL results. You must use ORDER BYthe WITH clause ROW_NUMBER()as it is mandatory. However PARTITION BYthe STRING clause is optional.

If you use both the PARTITION BYand ORDER BYclauses at the same time, the result will be undefined. Here, we will see how to use session variables to simulate ROW_NUMBER()the function to get the desired result.

Note that ROW_NUMBER()this is not available prior to MySQL version 8.0. You can see what's new in MySQL version 8.0 here.


ROW_NUMBER()Using the Using ORDER BYClause in MySQL

We will just use the function with ORDER BYthe while ROW_NUMBER()clause and observe the results. Let us first create the table and fill it with some data.

Sample code:

# SQL Programming Using MySQL Version 8.27
CREATE TABLE `test_db`.`tb_student` (
 STUDENT_ID	INTEGER NOT NULL,
 FIRST_NAME	VARCHAR(30) NOT NULL,
 LAST_NAME	VARCHAR(30) NOT NULL,
 GENDER	VARCHAR(30) NOT NULL,
 CITY_NAME	VARCHAR(64) NOT NULL,
 EMAIL_ADDRESS	VARCHAR(64) NOT NULL,
 REGISTRATION_YEAR INTEGER NOT NULL,
 PRIMARY KEY	(STUDENT_ID)
);

This query will create a tb_studenttable called , which you can confirm in your MySQL database.

Use INSERTthe following syntax of query to insert six records into a table named tb_student.

# SQL Programming Using MySQL Version 8.27
INSERT INTO test_db.tb_student
(STUDENT_ID, FIRST_NAME, LAST_NAME, GENDER, CITY_NAME, EMAIL_ADDRESS, REGISTRATION_YEAR)
VALUES
(1,'Ayush','Kumar', 'Male', 'Washington', 'akuman@yahoo.com', 2010);

Then select all the data from the table to view it using the following query.

# SQL Programming Using MySQL Version 8.27
SELECT * FROM test_db.tb_student

Your table will contain the following data. You can also check and compare.

# SQL Programming Using MySQL Version 8.27
SELECT *,
    ROW_NUMBER() OVER(ORDER BY REGISTRATION_Year) AS row_numb
FROM test_db.tb_student;

After executing the above query, you will get the following result.

Looking at the output above, you can see that all the records are displayed, sorted by the year of registration (see the green box column). And row_numberis also as expected, starting at 1 and tb_studentincreasing as we read all the data from till the end of the table.


In MySQL, use PARTITION BYthe clauseROW_NUMBER()

We will use only the function with PARTITION BYthe clause ROW_NUMBER()and observe the result. We will also compare this output with the results obtained using the ROW_NUMBER()and clauses.ORDER BY

Sample code:

# SQL Programming Using MySQL Version 8.27
SELECT *,
    ROW_NUMBER() OVER(PARTITION BY REGISTRATION_Year) AS row_numb
FROM test_db.tb_student;

Now, you will get the following result.

Look at REGISTRATION_YEARthe column; it has 5 partitions ( 2010, 2011, 2012, 2013and 2014). partitionThere are two rows in the table for 2010, and the row numbers are assigned correctly (again, see the screenshot above). partitionThere is only one row for 2011, 2012, 2013, 2014; that's why you can row_numbsee in the column 1.

If we use PARTITION BYthe INSERT clause, then why is REGISTRATION_YEARthe column named in ascending order? Because PARTITION BYthe INSERT clause sorts the data in these partitions. Let us insert another record with REGISTRATION_YEARthe value of 2009 and observe the result.

# SQL Programming Using MySQL Version 8.27

INSERT INTO test_db.tb_student
(STUDENT_ID, FIRST_NAME, LAST_NAME, GENDER, CITY_NAME, EMAIL_ADDRESS, REGISTRATION_YEAR)
VALUES
(7,'Mashal','Naaz', 'Female', 'Florida', 'mashalnaaz@gmail.com', 2009);

SELECT *,
    ROW_NUMBER() OVER(PARTITION BY REGISTRATION_Year) AS row_numb
FROM test_db.tb_student;

You will now see the most recent records at the top.


In MySQL, use PARTITION BYthe and ORDER BYclausesROW_NUMBER()

Now, we will just use the function with the PARTITION BYand ORDER BYclauses ROW_NUMBER()to see if it still gives the correct row numbers.

Sample code:

# SQL Programming Using MySQL Version 8.27
SELECT *,
    ROW_NUMBER() OVER(PARTITION BY REGISTRATION_YEAR ORDER BY REGISTRATION_YEAR) AS row_numb
FROM test_db.tb_student;

After executing the above query, you will see the same output as using the ROW_NUMBER()and PARTITION BYclauses. See the following screenshot:

You see the columns with yellow background, which is what we expect. Here we will use session variables to assign row numbers correctly.


Using Session Variables in MySQL ReplicationROW_NUMBER()

MySQL does not provide correct ranking functionality when we use both PARTITION BYand clauses. In this case, we simulate it using . Session variables are user defined; you can see the details here.ORDER BY会话变量

Sample code:

# SQL Programming Using MySQL Version 8.27
SET @row_numb = 0;
SELECT *,
    (@row_numb:=@row_numb + 1) AS row_numb
FROM test_db.tb_student ORDER BY REGISTRATION_YEAR;

As you can see below, row_numbit starts at 1 and increases continuously.

How does it work? We first set the session variable using the @ prefix row_numband initialize it with 0. Then we select the data from the table, sort it and print it. (@row_numb:=@row_numb + 1)Just like incrementing and updating the value of the variable.


in conclusion

From the above discussion, we conclude that although we can use function in MySQL ROW_NUMBER()if we have version 8.0 or higher, but in some cases we have to use Session Variablesfor ranking purpose.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

If ELSE in MySQL

Publish Date:2025/04/11 Views:85 Category:MySQL

In this tutorial, we aim to explore how to use IF ELSE the statement in MySQL. One of the key roles of a data analyst is to gather insights from the data and produce meaningful results. It can be done with the help of several data filtering

DATETIME vs. TIMESTAMP in MySQL

Publish Date:2025/04/11 Views:117 Category:MySQL

DATETIME and TIMESTAMP are two different data types that can be used to store values ​​that must contain both a date and a time portion. In this article, we will understand how it is stored in the database and the memory required for ea

Execute multiple joins in one query in MYSQL

Publish Date:2025/04/11 Views:94 Category:MySQL

Have you ever wondered how to include multiple joins in one query in MySQL? You have come to the right place. Remember that joins allow us to access information from other tables. This information is included separately to avoid redundancy.

Joining 3 tables in MySQL

Publish Date:2025/04/11 Views:187 Category:MySQL

In this tutorial, we will learn how to join three tables in MySQL. Businesses and organizations may have to visualize three tables simultaneously based on certain matching columns common to all three tables. This operation is allowed in MyS

Use of UPDATE JOIN in MySQL

Publish Date:2025/04/11 Views:85 Category:MySQL

This tutorial will explain how to use the statement in MySQL database UPDATE JOIN . We generally use joins to iterate over the rows in a particular table which may or may not have similar rows in other tables. We can UPDATE use JOIN the cla

Multiple primary keys in MySQL

Publish Date:2025/04/11 Views:66 Category:MySQL

In this tutorial, our goal is to explore the concept of multiple primary keys for a table in MySQL. Many times, businesses and organizations have to assign certain columns as primary keys. This primary key has multiple uses and reasons to b

Displaying foreign keys in MySQL

Publish Date:2025/04/11 Views:55 Category:MySQL

In this tutorial, we aim to explore how to display foreign keys for tables and columns in MySQL. The type of key that references a primary key, also known as the primary key of another table, is called a foreign key. Understanding the forei

Select first N rows in MySQL

Publish Date:2025/04/11 Views:85 Category:MySQL

Sometimes, you have to select first N rows of MySQL database according to your project requirements. n The value of varies according to the requirement; it can be TOP 1 row or TOP 30 rows. We will learn how to select top N rows using the cl

Copying a Database in MySQL

Publish Date:2025/04/11 Views:105 Category:MySQL

Creating a copy of an existing database is known as the MySQL Clone method. Cloning involves creating a copy of the table structure, constraints, functions, procedures, triggers, and all functionality associated with the table in one go. Th

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial