Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL LIMIT, but from the end

Tags:

sql

postgresql

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
like image 618
nicholaides Avatar asked Jan 16 '23 07:01

nicholaides


1 Answers

should be this way-

SELECT * FROM (
SELECT *
FROM PEOPLE
ORDER BY AGE DESC
LIMIT 3 ) X
ORDER BY AGE ASC
like image 57
Kshitij Avatar answered Jan 24 '23 23:01

Kshitij