This query will return ten items from the first page of the resultset. Increasing the offset value to 10 will return the second set of ten items. Increasing to 20 will return the third set of ten items, and so forth.
Here's a visual example of how it works. The first resultset with the offset value set to 0 returns the first set or page of items:
And the second resultset with the offset value set to 10
returns the second set of items:
The first record returned in your resultset will always have an index of 0, so your first offset value should also being with this value.
Also notice that the offset
value increases by the same amount as the limit
value. Using any other value would skip over records in your resultset. Meaning potential customers on your website searching for products would never see them in the search results because they weren't returned.
Here's a real-world example of how an offset calculation works to determine the page number to return. Say you have a function that accepts a parameter page
. Remember the default offset value of 0 is the first record, so our calculation could be as simple as this:
limit = 10;
offset = page * limit;
limit
is preset to 10 for each page.offset
is then calculated by multiplying the referenced page
parameter value by the limit
, returning 0, 10, 20, 30, etc. in sequence.LIMIT
with the OFFSET
ClauseAnother very similar way you could format how this code looks in MySQL is to remove the comma-separated list of offset and limit values and use the OFFSET
clause in its place. So instead of writing the LIMIT
clause in MySQL like this:
LIMIT 20, 10
You could quickly rewrite it to this:
LIMIT 10 OFFSET 20
Both return the same results with no difference in response time.
There's a lot of explanation here for such a simple process. I wanted to present every possible angle to help you fully understand how MySQL limits, offsets, and pagination work. Hope that helps. Happy coding!
Comments
There are no comments yet. Start the conversation!