Tag: T-SQL

  • Basic OFFSET–#SQLNewBlogger

    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:

    <query>
    ORDER BY col1, col2
    OFFSET n ROWS FETCH NEXT 10 ROWS ONLY

    This code:

    WITH myTally(n)
    AS
    (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)
    )
    SELECT *
    FROM myTally
    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.

    2021-04-19 13_56_15-SQLQuery5.sql - ARISTOTLE.DMDemo_5_Prod (ARISTOTLE_Steve (61))_ - Microsoft SQL

    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.

    2021-04-19 13_58_58-SQLQuery5.sql - ARISTOTLE.DMDemo_5_Prod (ARISTOTLE_Steve (61))_ - Microsoft SQL

    If I only want a certain number, say 6 rows, I add the FETCH clause.

    2021-04-19 13_59_40-SQLQuery5.sql - ARISTOTLE.DMDemo_5_Prod (ARISTOTLE_Steve (61))_ - Microsoft SQL

    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.

    SQLNewBlogger

    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.

  • Basic Fetch and Offset Experiments–#SQLNewBlogger

    I’ve never used the FETCH or OFFSET commands for pagination, but I have heard of them. I ran across them recently and decided to experiment a bit.

    One note: I have seen notes about performance, so before you do more than experiment, read about the issues (SQLPerformance, Use the Index, Luke)

    This is part of the ORDER BY clause, and this allows you to skip a number of rows and then also only get a certain number of rows in the result set. The basic syntax is:

    … ORDER BY XX
    OFFSET YYY ROWS
    FETCH {FIRST|NEXT} ZZZ ROWS

    This means, if I have a query link this one, I get the first ten rows with a 0 offset.

    SELECT 
      f.FlightDate, f.DepartureAirport, f.DestinationAirport
      FROM dbo.Flight AS f
      ORDER BY f.FlightDate
      OFFSET 0 ROWS
      FETCH FIRST 10 ROWS ONLY

    If I want the next 10, I can change the offset to 10.

    SELECT 
      f.FlightDate, f.DepartureAirport, f.DestinationAirport
      FROM dbo.Flight AS f
      ORDER BY f.FlightDate
      OFFSET 10 ROWS
      FETCH NEXT 10 ROWS ONLY

    The OFFSET must proceed the FETCH, and OFFSET can be 0. If I want to make this page, I need to ensure I change the value for OFFSET to skip the rows already returned. I can use variables here:

    DECLARE @offset INT = 2
    , @fetch INT = 4;

    SELECT 
      f.FlightDate, f.DepartureAirport, f.DestinationAirport
      FROM dbo.Flight AS f
      ORDER BY f.FlightDate
      OFFSET @offset ROWS
      FETCH FIRST @fetch ROWS ONLY

    This gets me the 3rd through 6th rows in my dataset. I’ve included a vertical partition here to let me test without having to remember which rows are which.

    2021-03-22 14_36_31-SQLQuery1.sql - ARISTOTLE_SQL2017.way0utwest (ARISTOTLE_Steve (57))_ - Microsoft

    This is a really basic look at the native way for paging through data, though beware the entire query runs and then the engine filters out data. This may or not be a big performance issues, but on large amounts of data it will be.

    SQLNewBlogger

    A quick look at a feature I ran across. I needed to test code for someone and verify it works, which means I needed to take 10 minutes and try a few queries. This entire post took my about 15 minutes to write and it gives me ideas for other posts.

  • T-SQL Tuesday #136–The Datatype Blog

    tsqltuesdayIt’s that time of the month again, and this time it’s an interesting topic. The invitation is from Iceland, where Brent Ozar has relocated for the foreseeable future. I’m slightly jealous, and wish I could go visit. I enjoy winter, and the pictures he’s posted look amazing. Definitely a bucket list trip for me.

    However, this month, he’s asking about data types. Are there some you love or hate, and I’ve got a thought on this. In case you wonder, there is a list, broken into types. Apparently MS went into a “categorize everything” frenzy in the docs, which is OK, but I often don’t intuit the way they’ve broken things down. I wish they kept a long list on a page somewhere that was easy to find.

    Naming Confusion

    It has been deprecated, but the timestamp type is still around. It’s not in the list, but it is mentioned as a synonym for rowversion. This is a unique binary number in each database, which is often used to detect changes in a row. If you have two people editing a row, and a change updates a rowversion column, then each can detect if that value is different from the original one. Handy in terms of client side conflict resolution, which can prevent last-writer-wins scenarios for applications.

    I haven’t seen it used lately, but in the 90s and early 2000s, I often saw code that checked this before letting a user make an update in some data entry application. However, this was often a “timestamp” column, which was constantly confusing to me as a DBA or developer. I kept thinking I’d get some sort of datetime stamp in there, rather than a binary value.

    This shouldn’t be a problem in the future, as timestamp isn’t really doc’d, though timestamp can be found on Google searches. 

    The other reason I dislike this type is that we can’t change it to rowversion. An ALTER TABLE … ALTER COLUMN doesn’t work.

  • Logging Messages with Raiserror – #SQLNewBlogger

    Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.

    I recently ran across some people discussing how to log some information in a script. One person was using PRINT, which I often use for quick checks, but someone else noted the RAISERROR works well, and you can customize messages.

    For example, I can have this type of script:

    DECLARE @d VARCHAR(20);
    

    -- do stuff

    SELECT @d = CAST( SYSDATETIME() AS VARCHAR(20));
    RAISERROR('%s - something happened at this time', 0, 1, @d)

    This allows me to add information into an error message. I can certainly construct @d with other stuff and then use that in PRINT, but I could get out of order messages. If  I add NOWAIT, I can ensure my messages get returned immediately.

    There are lots of options with RAISERROR, which I still use in place of THROW at times. While I like THROW, I think it doesn’t always give me the options I want for error handling, such as logging to the Windows lots.

    SQL NewBlogger

    When I saw this, I realized that I didn’t know, or remember, some of the ins and outs of RAISERROR, so I spent a few minutes looking through docs and playing with the code. I then wrote this quick post to help me remember a bit more.

    Short and quick is a good way to structure posts. I didn’t walk about all the options or ways I can use things. I’ll do some of that in another post.