I have some table that I want to query using cursor based pagination, but it needs to apply for multiple columns.
Let's take a simplified example of using 2 columns - I fetch the first page like this:
SELECT column_1, column_2
FROM table_name
ORDER BY column_1, column_2
LIMIT 10
After I get the results, I can fetch the next page based on the last row. Let's say the last row was column_1 = 5, column_2 = 8
. I'd like to do something like this:
SELECT column_1, column_2
FROM table_name
WHERE column_1 > 5 AND column_2 > 8
ORDER BY column_1, column_2
LIMIT 10
But this is obviously wrong. It would filter out a row that has column_1 = 5, column_2 = 9
(because of the filter on column_1
) or a row that has column_1 = 6, column_2 = 6
(because of the filter on column_2
)
I can do something like this to avoid the problem:
SELECT column_1, column_2
FROM table_name
WHERE column_1 > 5
OR (column_1 = 5 AND column_2 > 8)
ORDER BY column_1, column_2
LIMIT 10
But this becomes very cumbersome and error prone for more than 2 columns...
Also, my use case includes columns of multiple types (INT UNSIGNED
and BINARY
), but all are comparable
Do you have any suggestions?
Thanks!
WHERE
. But it is efficient. See also mysql.rjweb.org/doc.php/…