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.