SQL Query to Get Last Record from Table (With Example & 4 Easy Methods)
π Introduction
SQL query to get last record from table is a common requirement in database operations and SQL interviews.
Developers often need to fetch the most recent or last inserted record from a table for reporting, auditing, or application logic.
In this guide, you will learn:
- β How to get the last record in SQL
- β 4 easy methods with examples
- β Database-specific queries (MySQL, SQL Server)
- β Interview tips
π What is the Last Record in SQL?
The βlast recordβ usually means:
- The record with the highest ID
- Or the most recent entry based on date/time column
π§ͺ Sample Table
Id INT,
Name VARCHAR(50),
CreatedDate DATETIME
);
(1, ‘John’, ‘2024-01-01’),
(2, ‘Amit’, ‘2024-02-01’),
(3, ‘Sara’, ‘2024-03-01’),
(4, ‘David’, ‘2024-04-01’);
β Method 1: Using ORDER BY DESC (Most Common)
FROM Employees
ORDER BY Id DESC;
β For MySQL:
FROM Employees
ORDER BY Id DESC
LIMIT 1;
β This is the easiest sql query to get last record from table
β Method 2: Using MAX() Function
FROM Employees
WHERE Id = (SELECT MAX(Id) FROM Employees);
π Finds record with highest ID
β Method 3: Using ROW_NUMBER()
FROM (
SELECT *,
ROW_NUMBER() OVER (ORDER BY Id DESC) AS RowNum
FROM Employees
) t
WHERE RowNum = 1;
π Useful in complex queries
β Method 4: Using Date Column
FROM Employees
ORDER BY CreatedDate DESC
LIMIT 1;
π Best when using timestamp/date
π When to Use Which Method?
| Method | Best Use |
|---|---|
| ORDER BY DESC | Simple queries |
| MAX() | When ID is primary key |
| ROW_NUMBER() | Complex logic |
| Date Column | Latest record based on time |
β οΈ Important Points
- Ensure column used for sorting is correct
- Use indexed columns for better performance
- Handle duplicate values carefully
π― Interview Questions
- How do you get the last record in SQL?
- Difference between MAX() and ORDER BY?
- How to fetch latest record using date?
- What if ID is not sequential?
β Frequently Asked Questions :
Β
1. What is the SQL query to get last record from table?
You can use ORDER BY DESC with LIMIT 1 or TOP 1 to fetch the last record.
2. How to get last inserted record in SQL?
Use ORDER BY on ID or date column in descending order and fetch the top result.
3. Can we use MAX() to get last record?
Yes, MAX() returns the highest value, which can be used to get the last record.
4. Which method is best to get last record?
ORDER BY DESC with LIMIT or TOP is the most commonly used method.
5. How to get latest record using date column?
Sort the table using ORDER BY date column DESC and fetch the first row.