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?
DESCto the sort order there. – Erwin Brandstetter Jun 04 '23 at 23:29ORDER BYyou may get the rows in any order – Charlieface Jun 05 '23 at 11:33