If this:
SELECT *
FROM Table
WHERE Date=( SELECT MAX(Date)
FROM Table
)
returns newest record from the table, how to get second newest record?
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.
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.
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 .
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.
"select TOP (1) * from Table WHERE Date<(SELECT MAX(Date) FROM Table) ORDER BY Date DESC"
should do the trick.
Please check this code.
SELECT * FROM category
WHERE Created_Time <(
SELECT MAX(Created_Time)
FROM category
)
ORDER BY Created_Time DESC
LIMIT 1
Prasad.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With