HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

postgresql - paginate correctly ordering by non-distinct values?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqldistinctnonorderingpaginatevaluescorrectly

Problem

How can I properly page by ordering on a column that could possibly have repeated values? I have a table called posts, which has a column that holds the number of likes of a certain post, called num_likes, and I want to order by num_likes DESC. But, the image below shows a problem that I run into - the new row inserted between the two pages causes repeated data to be fetched.

This link here explains the problem, and gives the solution of keyset pagination, but from what I've seen, that only works if the column that the rows are being sorted on are distinct / unique. How would I do this if that is not the case?

Solution

I believe the simplest solution is to sort on multiple columns (the one(s) you need for your basic sort, plus another column (or set of columns) that would make the effective "key" of your query unique).

This is more difficult (but may not be impossible) if your table(s) don't have a primary or unique key; you'd have to establish that there is a set of columns that could uniquely identify the rows you're presenting.

Context

StackExchange Database Administrators Q#225209, answer score: 2

Revisions (0)

No revisions yet.