views:

88

answers:

4

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 ?


EDIT: To be explicit, I want to get all of the fields of that record . .

+4  A: 

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.

Zyphrax
what if i want to get the name as well for this record
ooo
+3  A: 
SELECT TOP 1 ID, Name, Score, [Date]
FROM myTable
WHERE ID = 2
Order BY [Date]
shahkalpesh
A: 

Try

select * from dataset
where id = 2
order by date limit 1

Been a while since I did sql, so this might need some tweaking.

Aaron
A: 

Using "limit" and "top" will not work with all SQL servers (for example with Oracle). You can try a more complex query in pure sql:

select mt1.id, mt1."name", mt1.score, mt1."date" from mytable mt1
where mt1.id=2
and mt1."date"= (select min(mt2."date") from mytable mt2 where mt2.id=2)
Jakub