How to fetch only N rows at a time in MySQL?


To fetch only N rows at a time, you can use LIMIT operator. Following is the syntax −

select *from yourTableNameLIMIT 0,N;

Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable(Name) values('John');
Query OK, 1 row affected (0.08 sec)

mysql> insert into DemoTable(Name) values('Larry');
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable(Name) values('Bob');
Query OK, 1 row affected (0.08 sec)

mysql> insert into DemoTable(Name) values('Sam');
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable(Name) values('Mike');
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(Name) values('Carol');
Query OK, 1 row affected (0.05 sec)

mysql> insert into DemoTable(Name) values('Ramit');
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(Name) values('Adam');
Query OK, 1 row affected (0.03 sec)

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(Name) values('Robert');
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(Name) values('James');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable(Name) values('Jace');
Query OK, 1 row affected (0.05 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+--------+
| Id | Name   |
+----+--------+
|  1 | John   |
|  2 | Larry  |
|  3 | Bob    |
|  4 | Sam    |
|  5 | Mike   |
|  6 | David  |
|  7 | Carol  |
|  8 | Ramit  |
|  9 | Adam   |
| 10 | Chris  |
| 11 | Robert |
| 12 | James  |
| 13 | Jace   |
+----+--------+
13 rows in set (0.00 sec)

Following is the query to fetch only N rows at a time. Here, we are fetching only 10 rows −

mysql> select *from DemoTable LIMIT 0,10;

This will produce the following output −

+----+-------+
| Id | Name  |
+----+-------+
|  1 | John  |
|  2 | Larry |
|  3 | Bob   |
|  4 | Sam   |
|  5 | Mike  |
|  6 | David |
|  7 | Carol |
|  8 | Ramit |
|  9 | Adam  |
| 10 | Chris |
+----+-------+
10 rows in set (0.00 sec)
raja
Published on 17-May-2019 18:34:15
Advertisements