Sample Header Ad - 728x90

Can you make Postgres execute ORDER BY after OFFSET and LIMIT?

0 votes
1 answer
887 views
Consider this pagination scenario | id | name | last_name | |--------:|----------:|--------:| | 1 | Mickey | Mouse | | 2 | Donald | Duck | | 3 | Scrooge | McDuck | | 4 | Minerva | Mouse | | 5 | Goofus | Dawg | | 6 | Daisy| Duck|
SELECT * FROM users
ORDER BY id DESC
LIMIT 3;
The result set is going to be | id | name | last_name | |--------:|----------:|--------:| | 6 | Daisy| Duck| | 5 | Goofus | Dawg | | 4 | Minerva | Mouse | It may make sense from SQL's standpoint, but it makes little sense from the human standpoint. After all, the query was meant as "give me the first page of three in reversed order". "The first page" is clearly the *first* three rows of the table, not the *last* three rows so the human way of executing that query would result in | id | name | last_name | |--------:|----------:|--------:| | 3 | Scrooge | McDuck | | 2 | Donald | Duck | | 1 | Mickey | Mouse | The original result set, on the other hand, would be a better fit for this query, "give me the *second* page of three in reversed order"
SELECT * FROM users
ORDER BY id DESC
LIMIT 3
OFFSET 3;
Can you make Postgres execute ORDER BY after OFFSET and LIMIT?
Asked by Sergey Zolotarev (243 rep)
Jun 4, 2023, 10:20 PM
Last activity: Jun 5, 2023, 02:03 AM