views:

431

answers:

2

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?

+4  A: 

[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
SELECT <some columns>
FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date ASC    
LIMIT 1
Mitch Wheat
I think the 'Top' keyword is for SQL server only, MySQL/Postgre uses 'Limit'
Robo
You are correct. I will edit mine and vote up yours.
Mitch Wheat
Good on yer, Mitch. I was wondering how many upvotes **I** could get if I posted an incorrect answer.
pavium
Using UNION ALL will make this marginally faster, as it removes a check for duplicates. It'll differ in how it works if the first and last row are the same of course - UNION will return just one row, UNION ALL will return the same row twice.
Magnus Hagander
@Magnus Hagander: I'm not sure it will be any faster when there is at most 2 rows. Granted, I would normally make the distinction between UNION and UNION ALL.
Mitch Wheat
@pavium: no idea.
Mitch Wheat
+8  A: 

First record:

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

Last record:

SELECT <some columns> FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date DESC
LIMIT 1
Robo
+1 Not every task must be done in a single query.
Bill Karwin
The UNION ALL method mentioned in the other comment will definitely be faster than issuing two queries.
Magnus Hagander