Postgresql – paginate correctly ordering by non-distinct values

postgresql

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?

new row problem pagination

Best Answer

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.