Whenever I run a query which contains both the LIMIT and the ORDER BY keywords, I get inconsistent results depending on the number of items specified in the LIMIT clause:
For example, the following query:
SELECT "people"."name"
FROM "people"
WHERE "people"."type" = 2
ORDER BY score desc, number desc
LIMIT 50
gives me this as a result:
[John, Jack, Amy, Brad, Tom, ...]
(John and Jack both have the same values for their score and number attributes. So do Amy, Brad, and Tom, in fact.)
Now, when I run:
SELECT "people"."name"
FROM "people"
WHERE "people"."type" = 2
ORDER BY score desc, number desc
LIMIT 5
I get the following result:
[Jack, John, Tom, Amy, Brad]
When the order by value is the same, the database can decide what the next sort is, and it's possible it may change over many runs of the same query.
Try adding a secondary order by
ORDER BY score, name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With