I have the following query in postgres:
SELECT *
FROM "bookings"
WHERE ("bookings".client_id = 50)
ORDER BY session_time DESC
LIMIT 20 OFFSET 0
The record in the 20th place is has an identical session_time to the 21st record.
This query returns 20 results, however if you compare the results to the whole database the query returns the 1st-19th results and the 21st, skipping over the 20th.
This query can be fixed by adding, "id" to the order:
SELECT *
FROM "bookings"
WHERE ("bookings".client_id = 50)
ORDER BY session_time DESC, id
LIMIT 20 OFFSET 0
However I was wondering how this bug occurred? How does postgres order identical filed when using offsets and limits? Is it random? Is it a bug with postgres?
order by
at all and expecting the results to be sorted in a particular order. No guarantees that they will. – Martin Smithsession_time
, and the planner will give you the fastest plan that does that; it makes no assumptions about what else you might want to order by that you didn't state. Just for fun, update one of those rows (even to current values) and do aSELECT
without anORDER BY
clause. If you want things in a particular order, you need to specify that. – kgrittnorder by
) – a_horse_with_no_name