Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return second newest record in SQL?

Tags:

sql

sql-server

If this:

SELECT *
FROM Table
WHERE Date=( SELECT MAX(Date)
             FROM Table
           )

returns newest record from the table, how to get second newest record?

like image 298
Davor Zubak Avatar asked Dec 21 '11 13:12

Davor Zubak


People also ask

How do I get the second last record in SQL?

Here is the query to get the second last row of a table in MySQL. mysql> select *from secondLastDemo order by StudentId DESC LIMIT 1,1; The output displays the second last record.

How do I get the latest row in SQL?

To get the last record, the following is the query. mysql> select *from getLastRecord ORDER BY id DESC LIMIT 1; The following is the output. The above output shows that we have fetched the last record, with Id 4 and Name Carol.

How do I get last 3 records in SQL?

I want to select the last 3 rows of an sql table. I know I should use SELECT * FROM table ORDER BY DESC LIMIT 3 , but the problem with this code is that it selects the rows from the end. For example, it selects 30, then 29, then 28. But, I need them in this format: 28, 29, 30 .


4 Answers

SELECT *  FROM Table WHERE Date = ( SELECT MAX(Date)                 FROM Table                WHERE Date < ( SELECT MAX(Date)                                FROM Table                             )              ) ; 

or:

SELECT TOP (1) *  FROM Table WHERE Date < ( SELECT MAX(Date)                 FROM Table              )  ORDER BY Date DESC ; 

or:

SELECT * FROM   ( SELECT t.*          , ROW_NUMBER() OVER(ORDER BY Date DESC) AS RowNumber     FROM Table t   ) AS tmp WHERE RowNumber = 2 ; 

If the Date column has unique values, all three queries will give the same result. If the column can have duplicate dates, then they may give different results (when there are ties in 1st or 2nd place). The first query will even give multiple rows in the result if there are ties in 2nd place.

like image 169
ypercubeᵀᴹ Avatar answered Sep 21 '22 22:09

ypercubeᵀᴹ


"select TOP (1) *   from Table     WHERE Date<(SELECT MAX(Date) FROM Table)   ORDER BY Date DESC" 

should do the trick.

like image 32
Quasdunk Avatar answered Sep 19 '22 22:09

Quasdunk


Please check this code.

SELECT * FROM category 
WHERE Created_Time <(
                     SELECT MAX(Created_Time) 
                     FROM category
                     ) 
ORDER BY Created_Time DESC 
LIMIT 1

Prasad.

like image 45
Prasad Rajapaksha Avatar answered Sep 20 '22 22:09

Prasad Rajapaksha


select second last date in sql:

 SELECT MAX(YourDateColumn) FROM YourTable where ColumnId=2 and  YourDateColumn <
(SELECT MAX(YourDateColumn) FROM YourTable where ColumnId=2)

hope helps someone.

like image 25
Shaiju T Avatar answered Sep 19 '22 22:09

Shaiju T