Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

SQL Query to Get the Latest Record from the Table

  • Last Updated : 23 Sep, 2021

Getting the latest record from the table is a simple task, you do not have a need to get advanced knowledge of SQL. In this article, we will discuss the simplest and easier methods to get the latest record from the Table.

You might want to get the latest record from the table with all the columns or you might want only a specific number of columns. You will get the solutions to both the problems in this article. 

Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course  by GeeksforGeeks.

Latest record of all column:

Step 1: To solve the queries, firstly create a Table from which you want to extract the record. Here, created a table named Student having Student Data such as Student ID, First Name, Last Name, Age, and the Course of the Student. 

Query:



Create Table Student
(StudentID Int, StudentFirstName Varchar(40),
studentLastName Varchar(40),
Age Int, Course Varchar(60))

Step 2: Insert data into a table

Query:

Insert Into Student Values
(1001,'Sahil','Kumar',19,'B.Com'),
1002,'Himanshu','Saini',20,'B.Tech'),
1003,'Nikhil','Gandhi',20,'B.Tech'),
1004,'Pransh','Mehra',18,'B.Com'),
1005,'Sudhir','Sharma',19,'M.Tech')

Step 3: To see data entries we use the below query:

Query:

Select * From student;

Output:



Now to get the latest record from the table, we will use the following syntax:

Syntax:

Select Column_Name From Table_Name
Order By Column_Name Desc

The data that we get on the top of the table is our latest data,  we will use OrderBy Descending to get our record.

You have seen that the First Name of the Student is on the top of the list, while if we see in the creation of the table. Entered the name Sudhir as the last entry. This gave us the data of all the columns in the Table. 

Now let’s see how to get the record of a specific number of Columns.

SQL query to get the latest record with multiple columns from the table:

To get the latest record of a specific number of columns, we will use the following syntax:

Query:

Select Top 3 Column_Name From Table_Name
Order By Column_Name Desc

Have a look at the example underneath, it shows the record of the Students in the Table.

 

You have observed only 3 entries from the table, but the thing to notice here is that these are the latest 3 entries of the Table, Student. In this way, you can get the latest record of more than one column.

 

My Personal Notes arrow_drop_up
Recommended Articles
Page :