From ff2f3635cb2a65ce120a52b8a4617fa3e05a2c43 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 11 Dec 2023 12:50:25 -0600 Subject: [PATCH] Add Select Rows After An Offset as a MySQL TIL --- README.md | 3 ++- mysql/select-rows-after-an-offset.md | 32 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 mysql/select-rows-after-an-offset.md diff --git a/README.md b/README.md index 472d1fb..af60f0e 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1357 TILs and counting..._ +_1358 TILs and counting..._ --- @@ -566,6 +566,7 @@ _1357 TILs and counting..._ - [Dump A Database To A File](mysql/dump-a-database-to-a-file.md) - [Ignore Duplicates When Inserting Records](mysql/ignore-duplicates-when-inserting-records.md) - [List Databases And Tables](mysql/list-databases-and-tables.md) +- [Select Rows After An Offset](mysql/select-rows-after-an-offset.md) - [Show Create Statement For A Table](mysql/show-create-statement-for-a-table.md) - [Show Tables That Match A Pattern](mysql/show-tables-that-match-a-pattern.md) - [Show Indexes For A Table](mysql/show-indexes-for-a-table.md) diff --git a/mysql/select-rows-after-an-offset.md b/mysql/select-rows-after-an-offset.md new file mode 100644 index 0000000..89b1e1a --- /dev/null +++ b/mysql/select-rows-after-an-offset.md @@ -0,0 +1,32 @@ +# Select Rows After An Offset + +When doing pagination and other queries for special-case scenarios, we may need +to grab rows after a certain offset. + +There are two variations of the MySQL syntax for selecting rows after a certain +offset. + +```sql +select * from events limit 100, 10; +``` + +This first query will grab up to 10 rows after applying an offset of 100. +Typically we'll see a `limit` clause with just one value which represents how +many rows to limit the result set to. However, if we optionally include `N, ` +in the middle of that clause. Whatever number `N` is will be the offset. + +Another way to write this is: + +```sql +select * from events limit 10 offset 100; +``` + +This gets the same result: 10 rows after an offset of 100. This is perhaps a +bit more straightforward and reduces the chance that we forget which value is +which like we might in the first syntax variation. + +Note: row ordering is only deterministic if you specify an order. To get +consistent results with `offset`, you'll most likely want to be specifying an +`order by` clause as well. + +[source](https://dev.mysql.com/doc/refman/8.0/en/select.html)