Tutorial :How to get the First and Last Record of DB



Question:

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

Note : I am not going do to order by


Solution:1

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  


Solution:2

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)  


Solution:3

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)


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »