How to fetch the newly added records from a MySQL table?



For this, you can use ORDER BY with LIMIT. Here, LIMIT is used to set the limit (count) of records you want to fetch. Let us first create a table −

mysql> create table DemoTable1486
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(20)
   -> );
Query OK, 0 rows affected (0.66 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1486(StudentName) values('Chris Brown');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1486(StudentName) values('David Miller');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1486(StudentName) values('John Doe');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1486(StudentName) values('John Smith');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1486(StudentName) values('Adam Smith');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1486(StudentName) values('Carol Taylor');
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1486;

This will produce the following output −

+-----------+--------------+
| StudentId | StudentName  |
+-----------+--------------+
|         1 | Chris Brown  |
|         2 | David Miller |
|         3 | John Doe     |
|         4 | John Smith   |
|         5 | Adam Smith   |
|         6 | Carol Taylor |
+-----------+--------------+
6 rows in set (0.00 sec)

Here is the query to get the newly added records −

mysql> select * from DemoTable1486
   -> order by StudentId desc
   -> limit 3;

This will produce the following output −

+-----------+--------------+
| StudentId | StudentName  |
+-----------+--------------+
|         6 | Carol Taylor |
|         5 | Adam Smith   |
|         4 | John Smith   |
+-----------+--------------+
3 rows in set (0.00 sec)

Advertisements