 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to select only 3 ordered rows on a MySQL table?
For this, you can use ORDER BY clause along with LIMIT. Let us first create a table −
mysql> create table DemoTable1551 -> ( -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> EmployeeName varchar(20) -> ); Query OK, 0 rows affected (0.52 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1551(EmployeeName) values('Chris'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable1551(EmployeeName) values('Robert'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1551(EmployeeName) values('Mike'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1551(EmployeeName) values('Sam'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1551(EmployeeName) values('David'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable1551(EmployeeName) values('Adam'); Query OK, 1 row affected (0.11 sec) Display all records from the table using select statement −
mysql> select * from DemoTable1551;
This will produce the following output −
+------------+--------------+ | EmployeeId | EmployeeName | +------------+--------------+ | 1 | Chris | | 2 | Robert | | 3 | Mike | | 4 | Sam | | 5 | David | | 6 | Adam | +------------+--------------+ 6 rows in set (0.00 sec)
Following is the query to select only 3 ordered rows in a MySQL table −
mysql> select * from DemoTable1551 -> order by EmployeeId desc limit 0,3;
This will produce the following output −
+------------+--------------+ | EmployeeId | EmployeeName | +------------+--------------+ | 6 | Adam | | 5 | David | | 4 | Sam | +------------+--------------+ 3 rows in set (0.00 sec)
Advertisements
 