SQL Query to Get the Latest Record from the Table
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.
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.
Create Table Student (StudentID Int, StudentFirstName Varchar(40), studentLastName Varchar(40), Age Int, Course Varchar(60))
Step 2: Insert data into a table
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:
Select * From student;
Now to get the latest record from the table, we will use the following 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:
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.
Please Login to comment...