Recovering Deleted Data

How to retrieve last 5 records in SQL?

Retrieve the last 5 records in SQL with TOP or LIMIT and an ORDER BY column, and see why deleted rows never appear in the output of that query.

On this page
  1. Use TOP or LIMIT with ORDER BY
  2. Choose a column that reflects insert order
  3. Return the five rows oldest first
  4. Deleted rows don’t show up

Use TOP or LIMIT with ORDER BY

To get the last five records, sort the table so the newest rows come first, then keep the first five. In SQL Server, use TOP:

SELECT TOP (5) OrderID, CustomerID, OrderDate
FROM dbo.Orders
ORDER BY OrderID DESC;

In MySQL and PostgreSQL, the same idea uses LIMIT:

SELECT OrderID, CustomerID, OrderDate
FROM orders
ORDER BY OrderID DESC
LIMIT 5;

“Last” only means something when the query has an ordering column. A SQL table has no inherent row order. Without ORDER BY, the five rows you get back can be any five rows, and they won’t necessarily be the most recent.

Choose a column that reflects insert order

An identity or sequence column such as OrderID often works, because its values usually grow with each insert, unless someone reseeds the column. A timestamp column such as CreatedAt also works, as long as it’s set when each row is inserted. If two rows can share the same value, add a second column to break the tie.

Return the five rows oldest first

The query above returns the newest row first. To show the same five rows in ascending order, wrap the query in a subquery and sort again on the outside:

SELECT OrderID, CustomerID, OrderDate
FROM (
    SELECT TOP (5) OrderID, CustomerID, OrderDate
    FROM dbo.Orders
    ORDER BY OrderID DESC
) AS last_five
ORDER BY OrderID ASC;

Deleted rows don’t show up

The query only sees rows still in the table. After a delete, the “last five” are the last five that survived, so the results can look as if a gap was skipped. To look for rows that are gone, use the checks in how to undo an accidental deletion. Whether the missing rows can come back depends on backups and other copies, as explained in is it possible to recover permanently deleted data.

The complete guide to recovering deleted data

How to Recover Deleted Data From a SQL Server Database
Read the guide

Keep exploring

Guides from other topics

All topics →