Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get First and Last record from a sql query?

Tags:

sql

postgresql

I have a table in PostgreSQL, I run a query on it with several conditions that returns multiple rows, ordered by one of the columns. In general it's:

SELECT <some columns>  FROM mytable <maybe some joins here> WHERE <various conditions> ORDER BY date DESC 

Now I'm only interested in getting the first and the last row from this query. I could get them outside of the db, inside my application (and this is what I actually do) but was wondering if for better performance I shouldn't get from the database only those 2 records I'm actually interested in.

And if so, how do I modify my query?

like image 804
kender Avatar asked Sep 28 '09 04:09

kender


People also ask

How do I get the first and last record in SQL?

To get the first and last record, use UNION. LIMIT is also used to get the number of records you want.

What is first and last function in SQL?

FIRST() SQL FIRST() function returns the first value of the given column. LAST() SQL LAST() function returns the last value of the given column.


1 Answers

[Caveat: Might not be the most efficient way to do it]:

(SELECT <some columns> FROM mytable <maybe some joins here> WHERE <various conditions> ORDER BY date DESC LIMIT 1)  UNION ALL  (SELECT <some columns> FROM mytable <maybe some joins here> WHERE <various conditions> ORDER BY date ASC     LIMIT 1) 
like image 50
Mitch Wheat Avatar answered Sep 16 '22 16:09

Mitch Wheat