26

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?

5 Answers 5

55

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
Sign up to request clarification or add additional context in comments.

2 Comments

That's it, thanks. I can accept only one (fastest) but all answers helped, sorry.
One of those answers that seems obvious in retrospect.
14

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)

Comments

8

Sub query may help you

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

Comments

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

or use

SELECT my_id, col2, col3 FROM mytable ORDER BY my_id DESC LIMIT 1

Comments

0

when you have an index on my_id the ones with the subquery should be faster. when you dont have an index take the "order by". (obv. depends on database size if relevant)

1 Comment

Probably the other way around. Postgres optimizes LIMIT 1 queries where an index is applicable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.