Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select most recent record based on date

Tags:

sql

sql-server

I'm trying to create a select query that returns the most recent record from the table based on date. Basically whichever row's [Date] field is closest to the current date.

Sample Data:

    ID       Content         Date
--------------------------------------------
1   1050    Test Values    2013-11-27 10:46:24.900
2   1051    Test Test      2013-11-27 10:47:43.150
3   1057    Test Testx2    2013-11-27 10:48:22.820

I would like to only return these values

    ID       Content         Date
--------------------------------------------
1   1057    Test Testx2    2013-11-27 10:48:22.820

Thanks!

like image 212
Justin Adkins Avatar asked Jan 25 '26 06:01

Justin Adkins


2 Answers

You could try the following query:

SELECT TOP 1 *
FROM Table
ORDER BY [Date] DESC
like image 132
Christos Avatar answered Jan 27 '26 18:01

Christos


Or, if you want your query to work on any DBMS (not just SQL Server), use ANSI SQL:

select * from t order by Date desc limit 1

or

select * from t where Date = (select max(Date) from t)
like image 33
dg99 Avatar answered Jan 27 '26 20:01

dg99



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!