 
  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 ORDER BY DESC and display the first 3 records in MySQL?
For this, you can use ORDER BY DESC with LIMIT. Let us first create a table −
mysql> create table DemoTable ( UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, UserName varchar(100) ); Query OK, 0 rows affected (0.59 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(UserName) values('Chris'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(UserName) values('Robert'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(UserName) values('Bob'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(UserName) values('David'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(UserName) values('Mike'); Query OK, 1 row affected (0.10 sec) Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------+----------+ | UserId | UserName | +--------+----------+ | 1 | Chris | | 2 | Robert | | 3 | Bob | | 4 | David | | 5 | Mike | +--------+----------+ 5 rows in set (0.00 sec)
Following is the query to display first 3 records after applying for ORDER BY DESC on a MySQL column −
mysql> select *from DemoTable order by UserId DESC LIMIT 0,3;
This will produce the following output −
+--------+----------+ | UserId | UserName | +--------+----------+ | 5 | Mike | | 4 | David | | 3 | Bob | +--------+----------+ 3 rows in set (0.00 sec)
Advertisements
 