Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: LIMIT + ORDER returning inconsistent results [duplicate]

Tags:

sql

postgresql

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]
like image 789
user2158382 Avatar asked Mar 03 '26 12:03

user2158382


1 Answers

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
like image 101
Diver Avatar answered Mar 06 '26 02:03

Diver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!