Select the next row after skipping every 2 rows in MySQL

MySQLMySQLi Database

To skip rows, you can use OFFSET. Let us first create a table −

mysql> create table DemoTable617(Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,FirstName varchar(100));
Query OK, 0 rows affected (1.70 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable617(FirstName) values('John');
Query OK, 1 row affected (0.39 sec)
mysql> insert into DemoTable617(FirstName) values('Sam');
Query OK, 1 row affected (0.39 sec)
mysql> insert into DemoTable617(FirstName) values('Carol');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable617(FirstName) values('Mike');
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable617(FirstName) values('David');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable617(FirstName) values('Bob');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable617(FirstName) values('Robert');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable617(FirstName) values('Chris');
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable617(FirstName) values('Mike');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable617(FirstName) values('Adam');
Query OK, 1 row affected (0.49 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable617;

This will produce the following output −

+----+-----------+
| Id | FirstName |
+----+-----------+
| 1 | John       |
| 2 | Sam        |
| 3 | Carol      |
| 4 | Mike       |
| 5 | David      |
| 6 | Bob        |
| 7 | Robert     |
| 8 | Chris      |
| 9 | Mike       |
| 10| Adam      |
+----+-----------+
10 rows in set (0.00 sec)

Following is the query to select rows. At first order by DESC. After that, it will skip two rows and display 5 rows using LIMIT 5 −

mysql> select tbl.* from (select *from DemoTable617 order by FirstName DESC LIMIT 5 OFFSET 2) AS tbl ORDER BY tbl.Id
;

This will produce the following output −

+----+-----------+
| Id | FirstName |
+----+-----------+
| 1 | John       |
| 4 | Mike       |
| 5 | David      |
| 8 | Chris      |
| 9 | Mike       |
+----+-----------+
5 rows in set (0.00 sec)
raja
Updated on 23-Aug-2019 06:21:05

Advertisements