nicholaides
nicholaides

Reputation: 19519

SQL LIMIT, but from the end

Can you LIMIT a query from the end of the results, rather than from the beginning? In particular, I'm looking for a solution w/ Postgresql, if that makes a difference.

Allow me to clarify with an example.

Let's say I want to return the 3 oldest people in my people table, but in ascending order of age. The best way I know how to select the 3 people returns the correct records, but in the reverse order:

SELECT * FROM people
ORDER BY age DESC
LIMIT 2

Upvotes: 7

Views: 5927

Answers (1)

Kshitij
Kshitij

Reputation: 8634

should be this way-

SELECT * FROM (
SELECT *
FROM PEOPLE
ORDER BY AGE DESC
LIMIT 3 ) X
ORDER BY AGE ASC

Upvotes: 9

Related Questions