Reputation: 35087
How can I retrieve the first and last record from a table.
Note : I am not going do to order by
Upvotes: 2
Views: 7230
Reputation: 23503
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
Upvotes: 11
Reputation: 1622
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)
Upvotes: 5
Reputation: 13306
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)
Upvotes: 2