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)