Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.
The other day I saw an article on the OFFSET clause in a SELECT. I had seen this come out and looked at it briefly in SQL Server 2012, but hadn’t done much with it.
NOTE: if you use this, be sure you read about potential performance problems and solutions.
The basic structure of this clause is that it is a part of the ORDER BY section of a query. After the column ordering, I can enter OFFSET and a value, which will skip those rows. I can optionally enter a number of rows to fetch.
The structure is:
ORDER BY col1, col2
OFFSET n ROWS FETCH NEXT 10 ROWS ONLY
(SELECT n = ROW_NUMBER() OVER (ORDER BY (SELECT null))
FROM (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)) a(n)
CROSS JOIN (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)) b(n)
ORDER BY n
Will get me numbers from 1 to 100, each in a separate row. A tally table, with partial results shown in this image.
If I change this, and add an OFFSET, I can skip some rows. For example, I can skip 7 rows by adding that clause, as shown below.
If I only want a certain number, say 6 rows, I add the FETCH clause.
This is useful for pagination, saving some network bandwidth, and less buffer space on the client. Not necessarily helping the query processor, but it does make it easy for developers and with small result sets (and source table sizes), this is nice.
It’s a fairly easy clause to use, but it can still require the full work on the server for looking through data, so be sure you read the link in the note above.
I was testing some code I’d seen from someone and it occurred to me to document the process a bit. I used a tally table, and wrote this around a couple of my experiments.
You can do this as well, show some learning, testing, understanding of code in ten minutes.