2

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!

7
  • What DB engine are you using? Commented Nov 27, 2013 at 15:55
  • We are using SQL Server 2008 Commented Nov 27, 2013 at 15:56
  • Try: SELECT TOP 1 * FROM <TableName> ORDER BY Date DESC Commented Nov 27, 2013 at 15:56
  • Date is not a valid name for a column; it is a type name. (SQL is not case sensitive) Commented Nov 27, 2013 at 15:58
  • @wildplasser I just used [Date] as an example. My actual column name is [Timestamp]. Commented Nov 27, 2013 at 16:00

4 Answers 4

6

You could try the following query:

SELECT TOP 1 *
FROM Table
ORDER BY [Date] DESC
Sign up to request clarification or add additional context in comments.

4 Comments

No, this gives the oldest entry and won't work as you're not specifying the fields you want to select or *.
@Thorten Thanks! It took me few seconds to check it in management studio, because I didn't remember the syntax of TOP
Yep, this worked. I simply changed * to the fields that I needed.
use brackets for date, is a reserved word in SQL Server 2008+
3

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)

Comments

1
SELECT TOP 1 * FROM Table ORDER BY [Date] DESC

This returns all fields from the first record after sorting from the highest date to the lowest. Essentially this returns the newest entry.

Comments

0
SELECT TOP 1  ID,Content,Date FROM <TABLE_NAME> ORDER BY Date

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.