Skip to content
Advertisement

How do I pull last 5 entry from a from a table through SQL query?

I have a table with data entry like below. I want to select the last 5 rows all the time when new data will be inserted. So, product_id 2-6 will be selected in here. But when I will enter a new product, id 3-7 will be selected and afterwards.. What will be SQL query for this? I am newbie. Any help will be greatly appreciated. Thanks in advance.

product_id   product_name   product_price
------------------------------------------
1            Phone         120
2            Chips         2
3            Television    300
4            PC            400
5            Radio         50
6            Watch         10

Advertisement

Answer

You can use the below query assuming that “product_id” is incremental as the new rows get added.

Select * from table_name order by product_id DESC limit 5.

Explanation: The query will sort the rows based on product_id in descending order and limit 5 will Limit the output to 5 from first row. So even a new row is added the query will give you the last five rows.

Hope it helps. Thanks

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement