select nth row in mysql

How to Find nth Row in MySQL

Sometimes you may need to select nth row or fetch nth record from your table. Here’s how to find nth row in MySQL.


How to Find nth Row in MySQL

Here are the steps to find nth row in MySQL. Let’s say you have the following sales table.

mysql> create table  sales(id  int, created_at date, sale int);

mysql> insert into sales(id, created_at,sale)
     values(1, '2020-01-01',100),
     (2, '2020-01-02',150),
     (3, '2020-01-03',200),
     (4, '2020-01-04',100),
     (5, '2020-01-05',150),
     (6, '2020-01-06',200),
     (7, '2020-01-07',100),
     (8, '2020-01-08',250);

mysql> select * from sales;
+------+------------+------+
| id   | created_at | sale |
+------+------------+------+
|    1 | 2020-01-01 |  100 |
|    2 | 2020-01-02 |  150 |
|    3 | 2020-01-03 |  200 |
|    4 | 2020-01-04 |  100 |
|    5 | 2020-01-05 |  150 |
|    6 | 2020-01-06 |  200 |
|    7 | 2020-01-07 |  100 |
|    8 | 2020-01-08 |  250 |
+------+------------+------+

Bonus Read : How to Replicate MySQL Database


How to Return Nth row in MySQL

Here’s the SQL query to find nth row in MySQL. Let’s say you want to return 3rd row.

mysql> select * from sales limit 2,1;
+------+------------+------+
| id   | created_at | sale |
+------+------------+------+
|    3 | 2020-01-03 |  200 |
+------+------------+------+

In the above query we use LIMIT clause to get the Nth row. If you want to select NTH row, then you need to use LIMIT N-1, 1 in your query.

Hopefully, the above query will help you fetch Nth row in MySQL.

mm

About Ubiq

Ubiq is a powerful dashboard & reporting platform. Build dashboards, charts & reports for your business in minutes. Try it for free!