Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (55.6k points)

Can anyone explain how to get the last 5 records in SQL?

3 Answers

0 votes
by (119k points)

Here is the syntax to get the last 5 records of the table in SQL:

SELECT * FROM

                (SELECT TOP 5 *

FROM table_name

                ORDER BY ID DESC

                )

ORDER BY id ASC;

In the above query, we used subquery with the TOP clause that returns the table with the last 5 records sorted by ID in descending order. Again, we used to order by clause to sort the result-set of the subquery in ascending order by the ID column.

If you want to take a course that can provide Instructor-led training and certification, I suggest this SQL Training by Intellipaat.

0 votes
by (37.3k points)
  • Let's assume an “employee” table which has employee_id, name, hiring_date as columns, we want to fetch last 5 records of the table. Query: Select * From ( Select * From employee Order by hiring_date DESC Limit 5) as subquery Order by hiring_date ASC; Subquery orders the data by hiring_data in descending order and limit it to 5 records. The outer query orders these 5 records in ascending order.

0 votes
by (3.1k points)

To retrieve the last five records in SQL, you may implement an ORDER BY clause together with LIMIT. This will arrange the entire records in a reverse order for the sake of sorting. Limiting the query to 5 will, therefore, provide me with 5 records only.

For an example:

SELECT * 

FROM tableName

ORDER BY colName DESC

LIMIT 5;

Related questions

0 votes
2 answers
asked Apr 22, 2020 in SQL by Sudhir_1997 (55.6k points)
0 votes
2 answers
0 votes
2 answers

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...