How to write a MySQL query to select first 10 records?

MySQLMySQLi Database

To select first 10 records, we can first order the records in ascending or descending order. With that, use LIMIT 10 to get only 10 records −

select *from (select *from yourTableName ORDER BY yourColumnName ASC LIMIT 10)anyAliasName ORDER BY yourColumnName DESC;

Let us first create a table −

mysql> create table DemoTable683(Page int);
Query OK, 0 rows affected (0.83 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable683 values(100);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable683 values(101);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable683 values(102);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable683 values(103);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable683 values(104);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable683 values(105);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable683 values(106);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable683 values(107);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable683 values(108);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable683 values(109);
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable683 values(110);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable683 values(111);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable683 values(112);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable683 values(113);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable683 values(114);
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable683;

This will produce the following output −

+------+
| Page |
+------+
|  100 |
|  101 |
|  102 |
|  103 |
|  104 |
|  105 |
|  106 |
|  107 |
|  108 |
|  109 |
|  110 |
|  111 |
|  112 |
|  113 |
|  114 |
+------+
15 rows in set (0.00 sec)

Following is the query to select first 10 records in MySQL −

mysql> select *from (select *from DemoTable683 ORDER BY Page ASC LIMIT 10)tbl ORDER BY Page DESC;

This will produce the following output −

+------+
| Page |
+------+
|  109 |
|  108 |
|  107 |
|  106 |
|  105 |
|  104 |
|  103 |
|  102 |
|  101 |
|  100 |
+------+
10 rows in set (0.00 sec)
raja
Published on 26-Aug-2019 11:14:50
Advertisements