September 202313:2084.9k views

Pagination in MySQL - offset vs. cursor

About

Limit/offset or cursor? Both have advantages and both have drawbacks. I start with deterministic ordering, then show how each one works: offset lets you jump to any page but throws away more rows the deeper you go and can skip records when the data shifts, while cursors fix both but can't jump to page 10.

Transcript

Everything I said

00:00

If you've got a billion records in your table, congratulations, by the way. You usually don't want to show your users all of those billion items at the same time. So instead, you will paginate the... Paginate? Paginate? Paginate. Paginate. Paginate. You would paginate the results and show the user a single page at a time.

00:26

There are two primary ways to paginate results in MySQL. The first is limit offset. The second is cursor-based pagination. And before you tell me that limit offset is terrible, they both have advantages, they both have disadvantages. Sometimes you will need to use limit offset to meet a business goal or a UI design or something like that.

00:49

And as much as I wish that developers were always in charge of everything all the time, most of the time we have bosses. So if you could be here around 9:00, that would be great. Mm-kay? I will remember you. Will you remember me?

01:09

Most of the time we have bosses, right? We can't just say, "I'm not gonna implement this feature or do it this way because I don't like the query that I'm writing." That doesn't normally work. So we're gonna look at both limit offset and cursor-based pagination, and we'll talk about the advantages and the disadvantages of each. Let's say we've got a table called people and we run select star from people and we'll get back this set of results.

01:32

All right, on this set of results, we want to show the users page one, page two, page three, let them navigate forward and backwards. This is what we're after. Before we can even talk about pagination, we have to talk about something called deterministic ordering. Deterministic ordering means that MySQL has enough information to order the rows in the same way every single time.

01:55

If we take this query, for example, so we're ordering by first name here. If we order by first name, is this deterministic ordering? Mm, no, not even close, because this is a valid result set and this is a valid result set. Both of those result sets are ordered by first name. As long as the results are ordered by first name, it is a valid result set that MySQL could return.

02:20

Okay, let's try this again. If first name is not deterministic enough, surely first name plus last name is deterministic enough. Here's the result set for first name and last name, but uh-oh, we've got two Aaron Andersons, which means we're still not deterministic. This is a valid result set and this is a valid result set. These could come back in any order and it still would be a legal and valid result set from MySQL.

02:45

If the order's constantly shifting around, users may see the same record on multiple pages and that is something we want to avoid. What if we were to order by first name, last name, and birthday? Well, that still could not be deterministic enough, so instead we're just gonna add ID. Anytime you add ID to the ordering columns, you are guaranteed that it is going to be deterministic because ID is your primary key.

03:08

So now MySQL's gonna order by first name and anytime there's a collision on first name, it's gonna order by ID and there will never be a collision on ID. Now that we have a deterministic order, we can start to paginate these records. We're gonna talk about limit offset first. We have this same query that we've been working with and now we're gonna add a limit ten to it and this tells MySQL, "Give me these first ten results." This is going to be our page one.

03:33

Implicit in this query is an offset zero. We're saying to MySQL, "Give me the first ten results, skipping zero results." So this is our page one. Now, if we were to change this offset to a ten, MySQL is going to skip over the first ten results and this becomes our page two. In the same way, we can say skip over the first 20 results and this becomes our page three.

03:58

So the offset determines how many results we're going to skip over and the limit determines the size of the page that is going to be returned. So we can generalize this a little bit by saying that limit is the page size and you can calculate the offset by taking the page size and multiplying it by the page number minus one. And this is one of the advantages of offset limit pagination is you can directly address any single page.

04:22

If you wanted to jump to page five, you could. You do not have to go through pages one, two, three, and four. You can jump directly to page five. If you wanted to jump to page 30, which we'll do now, you absolutely could. But one thing you may have noticed in that animation is we scrolled through the first 29 pages and that is one of the drawbacks of offset limit.

04:46

The higher the offset, the more data that MySQL is basically just throwing away. So it's constructing, it's constructing this result set and then it has to scroll all the way down, throwing away 290 records and giving you back the next ten. This is a drawback of offset limit pagination. It is not a drawback of cursor-based pagination, which doesn't suffer from this at all.

05:10

If we go back to the top, we're gonna look at another drawback of offset limit pagination and that's that the rows or the records can shift out from underneath you pretty easily. So in this case, the user is looking at page one, right? They're looking at page one. They see these first ten records. Now let's imagine that Zoey Hill, record number nine, is deleted while the user is looking at page number one.

05:33

So when the user goes to page number two, they should see Sonja Dickens, right? Because that's the first person that they have not seen yet. But if we watch what happens, we see that Sonja Dickens ends up being on page one while the user is navigating to page two, so the user never saw Sonja Dickens.

05:55

Because a record was deleted on page one and then we navigated to page two, Sonja ended up on page one and now we're on page two and we never saw Sonja. Sorry, Sonja. That's another drawback of offset limit pagination. It's not very resilient to shifting data. Let's move on to cursor-based pagination. We're gonna start with the same query.

06:15

This same query is going to show us page number one. Show me 10 items from this list, that's page number one. But instead of using an offset to calculate the next page, what we're going to do is we're going to say, "Let's keep track of the last record that I saw." In this case, the last record that we see on this first page is number 10, Judge Benz.

06:39

So what we're gonna do is we're going to create a cursor out of this last record. A cursor can go by many names. In the database world, a database cursor is a very specific thing, but what we're talking about is the concept of a cursor. Not a database cursor, but a concept of a cursor. And a cursor could go by many names. It could be a cursor, it could be a pointer, it could be a token, a key, a next, previous.

07:04

It could be any of these things. So what we're gonna say is that our cursor is an ID of 10, so this is the ID of the last person that we've seen. Now, typically, what will happen is this will get Base64 encoded and sent out to the client, whether that's an API, a front end, a mobile app, whatever. It gets sent out to the client as a part of the response.

07:26

Then what needs to happen is that client needs to take that next page key and send it back to the application or to the database, and then the database will decode it and say, "Okay, my next page key, or my token, or my cursor is an ID of 10." And now what we do with that token or that cursor is we take that cursor and we put it back into the query.

07:51

But we can't put it back into the query as ID equals 10. What we need to do is we need to say the last one that they saw was number 10, so let's convert that to ID greater than 10, and that will give us the very next record that they should see. As long as they tell us what the cursor of the last one that they have seen is, we can figure out what the next one they should see is.

08:13

Now, this gets a little bit more complicated if you're ordering by two things. In the last example, we were ordering by ID only, but what happens if you're ordering by first name and then ID? Your cursor always points to the last record that the user has seen, but it has to include every column that the user is sorting by. So in our case, we're sorting by first name and ID, and the last record that we see is this Aaron Runte guy.

08:37

So in this case, our cursor needs to include the first name of Aaron, but also the ID of 25995. So that gets Base64 encoded, sent out to the front, sent back, and now we have the cursor back of first name Aaron, ID 25995. And we can take that and put it intelligently into our query again. So now we're gonna say, "Show me people where the first name is equal to Aaron, but the ID is greater than the last ID that we have seen." It gets a little bit more complicated than

09:07

this, because this is showing us people named Aaron after the last Aaron that we have seen, but if this is the last Aaron, we need to see people with names greater than Aaron. So the more columns you add to cursor-based pagination, the more complicated this part becomes. Now, this is one of the drawbacks of cursor-based pagination. You never know what page two or three or four actually is.

09:31

You only know what is the next page after the page that I have already seen? So I'm gonna give you a cursor, which is a pointer to a record, and I want you to show me the records that come after that record. So with cursor-based pagination, there is no way to directly address a page. You cannot skip to page 10.

09:52

You can only go forwards and backwards. That's one of the drawbacks, but one of the benefits is we're not using offset, and because we're not using offset, we're not throwing away a bunch of data like we were in the limit offset method. Another benefit is that it's much more resilient to shifting records. So if we go back up to page one here, and let's say the last two people were deleted.

10:13

These Aarons were deleted while the user was looking at this page. Even if we stick with the same query and the same cursor from the previous example, this is still going to work. Even though the record that the cursor was based on has been deleted, this query will still work just fine, and notice that we don't miss the first two records on what is now the second page.

10:37

Because this cursor that we constructed doesn't directly reference that record at all, it's just based upon that record, when we construct a query out of that cursor, it's still gonna work even if that record is gone. That's probably more than you ever wanted to know about pagination, but now you know. Now you know what the trade-offs are. So limit offset is super easy to implement, and it's totally stateless.

11:00

You don't need to know what the last page was. You can just directly navigate to a page. You wanna go to page five? Fine. You wanna go to page 1,000? Fine. That, that is really, really easy to do. It is more prone to drifting. It's prone to those records changing out from under you, and if you delete a record, you might miss somebody on the navigation, right?

11:23

It's also very slow once you reach the deeper pages, because we're throwing away all of that offset data. There is a technique called a deferred join, and I'll put a few links in, in the description. A deferred join can help mitigate that slowness for deep pages, so you might read into that if you are gonna use limit offset method.

11:46

Cursor-based pagination or token or key set, whatever you wanna call it, it is more performant. So instead of generating this entire result set and throwing away the pages you don't need, you allow the database to jump directly to the page you do need. It's also more resilient to drift. Even if all of the records in the previous pages were deleted and your, your user sends you a token, they're still gonna get the next page of records, which is, which is really, really nice.

12:14

It's more complicated. It's more complicated. You have to be... You have to take great care in constructing those queries out of the cursor to make sure that you get all of those operators right, and if you're, if you're sorting on multiple columns, that just becomes more and more complicated, and you have to pass around that token. You have to pass around the state. The user has to tell you, "Here's the last thing that I've seen." You can't directly navigate to a page.

12:40

So if your user's on page one, they can't directly jump to page 10. That may not be a problem. That may not be a problem for your UI if you have an infinite scroll kind of thing. You only ever need to know what the next page is, and so you might, you might be fine there. Now that you know the difference between the two, you can choose whichever one, whichever one meets your application's needs.

13:01

If you liked this video, that's great. I'm really happy to hear that. We've got a lot more at planetscale.com/mysql, or on this channel. Until the next time, go forth and paginate. Paginate. Paginate. Go forth and paginate with confidence. See ya.

Databases

More videos on databases

All videos

Get the next one by email

I’ll send you some more. Not too many.

Join 7,500+ other readers.

Read past issues