Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL, SELECT from max id

By using libpq on PG 9.1, I am trying to write query to get values from row with highest index 'my_id':

SELECT my_id, col2, col3 
FROM mytable 
WHERE my_id = MAX(my_id)

That gives me error:

ERROR: aggregates not allowed in WHERE clause...

How to write such query properly?

like image 569
Wine Too Avatar asked Jun 05 '13 09:06

Wine Too


2 Answers

If your goal is to get the row with the highest my_id value, then the following query should achieve the same goal.

SELECT my_id, col2, col3 
FROM mytable 
ORDER BY my_id DESC 
LIMIT 1
like image 166
GordonM Avatar answered Oct 04 '22 22:10

GordonM


Just order by my_id and take only the first record with limit 1

SELECT my_id, col2, col3
FROM mytable 
order by my_id desc
limit 1

Another but less performant way would be

SELECT my_id, col2, col3
FROM mytable 
where my_id = (select max(my_id) from mytable)
like image 42
juergen d Avatar answered Oct 04 '22 20:10

juergen d