tags:

views:

174

answers:

3

How can I retrieve the first and last record from a table.

Note : I am not going do to order by

+2  A: 
SELECT TOP 1 * FROM Table ORDER BY 1
SELECT TOP 1 * FROM Table ORDER BY 1 DESC

assuming your first column is the key

(well that would work in t-sql)

mcintyre321
+7  A: 

Depends what you mean by "first" and "last".

You can "ORDER BY" a specific column, and choose "LIMIT 1", and then "ORDER BY ... DESC" to get the reverse.

e.g.

SELECT * FROM table ORDER BY col LIMIT 1
SELECT * FROM table ORDER BY col DESC LIMIT 1

...and if you want both in the same query:

SELECT * FROM table ORDER BY col LIMIT 1
UNION
SELECT * FROM table ORDER BY col DESC LIMIT 1
Jeremy Smyth
why not add a union statement between the queries?
lexu
No reason! Depends if the question wants that or not. I'll edit :)
Jeremy Smyth
+3  A: 

Question doesn't really make sense, but, assuming you're talking about the first and last row from a table this would work but it'd be better to do as two separate queries and assumes you have a numeric ID column. MySQL example:

select * from test where id = (select max(id) from test)
union
select * from test where id = (select min(id) from test)
Ian