Select specific rows in a range with MySQL?



Let us first create a table −

mysql> create table DemoTable    (    Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,    StudentName varchar(20)    ); Query OK, 0 rows affected (1.23 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(StudentName) values('John'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable(StudentName) values('Carol'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable(StudentName) values('David'); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable(StudentName) values('Bob'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(StudentName) values('Chris'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(StudentName) values('Robert'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(StudentName) values('Adam'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(StudentName) values('Mike'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(StudentName) values('Sam'); Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

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

Here is the query to select specific rows MySQL −

mysql> select *from DemoTable ORDER BY Id DESC LIMIT 4 OFFSET 2;

Output

+----+-------------+ | Id | StudentName | +----+-------------+ | 7 | Adam | | 6 | Robert | | 5 | Chris | | 4 | Bob | +----+-------------+ 4 rows in set (0.00 sec)
Updated on: 2019-07-30T22:30:26+05:30

624 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements