- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Select the topmost record from a table ordered by desc on the basis of ID?
For this, use ORDER BY DESC with LIMIT 1. Let us first create table −
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> UserName varchar(100), -> UserMessage text -> ); Query OK, 0 rows affected (1.17 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(UserName,UserMessage) values('Adam','Hi'); Query OK, 1 row affected (0.92 sec) mysql> insert into DemoTable(UserName,UserMessage) values('Chris','Awesome'); Query OK, 1 row affected (0.52 sec) mysql> insert into DemoTable(UserName,UserMessage) values('Robert','Nice'); Query OK, 1 row affected (0.65 sec) mysql> insert into DemoTable(UserName,UserMessage) values('David','Good Morning!!!'); Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
This will produce the following output −
+----+----------+-----------------+ | Id | UserName | UserMessage | +----+----------+-----------------+ | 1 | Adam | Hi | | 2 | Chris | Awesome | | 3 | Robert | Nice | | 4 | David | Good Morning!!! | +----+----------+-----------------+ 4 rows in set (0.00 sec)
Following is the query to select the topmost record from a table −
mysql> select *from DemoTable order by Id DESC limit 1;
Output
This will produce the following output −
+----+----------+-----------------+ | Id | UserName | UserMessage | +----+----------+-----------------+ | 4 | David | Good Morning!!! | +----+----------+-----------------+ 1 row in set (0.00 sec)
Advertisements