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

Β 
CREATE TABLE Employees (
Id INT,
Name VARCHAR(50),
CreatedDate DATETIME
);
Β 
Β 
INSERT INTO Employees VALUES
(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)

Β 
SELECT TOP 1 *
FROM Employees
ORDER BY Id DESC;
Β 

βœ… For MySQL:

Β 
SELECT *
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

Β 
SELECT *
FROM Employees
WHERE Id = (SELECT MAX(Id) FROM Employees);
Β 

πŸ‘‰ Finds record with highest ID


βœ… Method 3: Using ROW_NUMBER()

Β 
SELECT *
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

Β 
SELECT *
FROM Employees
ORDER BY CreatedDate DESC
LIMIT 1;
Β 

πŸ‘‰ Best when using timestamp/date


πŸš€ When to Use Which Method?

MethodBest Use
ORDER BY DESCSimple queries
MAX()When ID is primary key
ROW_NUMBER()Complex logic
Date ColumnLatest 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top