Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql query to get earliest date

Tags:

sql

sql-server

If I have a table with columns id, name, score, date

and I wanted to run a sql query to get the record where id = 2 with the earliest date in the data set.

Can you do this within the query or do you need to loop after the fact?

I want to get all of the fields of that record..

like image 679
leora Avatar asked Mar 06 '10 18:03

leora


People also ask

How do I get early date in SQL?

First, create an aggregate query that has two fields: GroupID and RecordDate. Group by the GroupID field, and choose the "Min" option for the RecordDate, to return the earliest date for each query.

How can I get 30 days before a date in SQL?

SELECT (column name) FROM (table name) WHERE (column name) < DATEADD(Day,-30,GETDATE()); Example.


2 Answers

If you just want the date:

SELECT MIN(date) as EarliestDate FROM YourTable WHERE id = 2 

If you want all of the information:

SELECT TOP 1 id, name, score, date FROM YourTable WHERE id = 2 ORDER BY Date 

Prevent loops when you can. Loops often lead to cursors, and cursors are almost never necessary and very often really inefficient.

like image 99
Zyphrax Avatar answered Oct 05 '22 05:10

Zyphrax


SELECT TOP 1 ID, Name, Score, [Date] FROM myTable WHERE ID = 2 Order BY [Date] 
like image 30
shahkalpesh Avatar answered Oct 05 '22 05:10

shahkalpesh