Tag: T-SQL

  • Duplicate Identity Values?

    Can you have duplicate values in a field with the identity property? Of course, and this does it.

    DROP TABLE dbo.MyTable
    
    CREATE TABLE mytable
    ( id INT IDENTITY(1,1)
    , mychar VARCHAR(10)
    )
    GO
    INSERT mytable SELECT 'A'
    INSERT mytable SELECT 'B'
    INSERT mytable SELECT 'C'
    
    
    SELECT * FROM dbo.MyTable

    This returns these values:

    result1

    Then we use Identity_insert

    SET IDENTITY_INSERT dbo.MyTable ON
    GO
    INSERT dbo.MyTable
            ( ID, myChar )
    VALUES  ( 8, -- myID - int
              'H'  -- myChar - varchar(20)
              )
    SET IDENTITY_INSERT dbo.MyTable OFF
    
    SELECT * FROM dbo.MyTable

    result2

    Now we reseed and add more values

    DBCC CHECKIDENT('mytable', RESEED, 4)
    
    INSERT mytable SELECT 'E'
    INSERT mytable SELECT 'F'
    INSERT mytable SELECT 'G'
    INSERT mytable SELECT 'H'
    INSERT mytable SELECT 'I'
    
    SELECT * FROM dbo.MyTable

    result3

     

    You can see that we have two ID rows with “8” in them. Clearly a duplicate.

    Identity doesn’t guarantee uniqueness. If you want that, make a PK or add a unique index.

  • Identity Reseeding

    I love the identity property. I use it in many of my tables, mostly because it gives me a fairly reliable surrogate key that I can use in my tables, especially when testing something. I often do something like this:

    CREATE TABLE MyIdentityTest
    ( id INT IDENTITY(1,1)
    , mychar VARCHAR(10)
    )
    GO
    INSERT MyIdentityTest SELECT 'A'
    INSERT MyIdentityTest SELECT 'B'
    INSERT MyIdentityTest SELECT 'C'
    GO

    In this table, I have these results:

    id          mychar

    ———– ———-

    1           A

    2           B

    3           C

    If I then look to reseed things for some reason, maybe I want to leave a gap somewhere, I can do this:

    SET IDENTITY_INSERT MyIdentityTest ON
    INSERT MyIdentityTest (id, mychar) SELECT 12, 'L'
    GO
    SET IDENTITY_INSERT MyIdentityTest OFF
    GO

    This means my table now looks like this.

    id          mychar

    ———– ———-

    1           A

    2           B

    3           C

    12          L

    If I insert a new value:

    INSERT MyIdentityTest SELECT 'M'
    GO
    

    And now check all the results, I have this:

    SELECT * FROM myidentitytest

    we get

    id          mychar

    ———– ———-

    1           A

    2           B

    3           C

    12          L

    13          M

     

    Suppose I realized that I had a problem and decided to “fix” my identity values. I can reseed like this, which sets the identity property tracker back to 3.

    DBCC CHECKIDENT(myidentitytest, RESEED, 3)
    go
    INSERT MyIdentityTest SELECT 'D'
    GO

    However look at the results of the insert. It shows 4 instead of 3, which is what I want in this case.

    SELECT * FROM myidentitytest

    id    mychar

    —– ———-

    1     A

    2     B

    3     C

    12    L

    13    M

    4     D

    Quite a few people think that if I set the identity to “3”, I should have 3 as the next value. That’s not the case, and it’s something to be aware of when working with identities. If you are looking to fill gaps or move your seed for some reason (like merge replication), understand that you are inserting the “last” value as your seed, not the “next” one.

  • Hints Are Not Always Better

    Is this better than an index scan?

    I have always thought that an index seen was preferable to an index scan. It seems like the general rule that so many DBAs and developers follow, looking to convert every scan in an execution plan to a seek. Often that results in better performance, and I’ve seen many people resort to using hints to enforce this behavior in SQL Server when the query optimizer (QO) or Query Processor (QP) fails to choose their indexes.

    This past week Rob Farley wrote a great blog post that taught me something about seeks, scans, and the fact that one is not always better than the other. It has a great title and is worth a few minutes of your time to read: Covering, schmuvvering – when a covering index is actually rubbish. In the post Rob shows that a seek can be worse than a scan in some cases, in his example due to a Residual Predicate.

    I have seen so many people mistrust the query processor in SQL Server over the years, often resorting to hints when it seemed that the best index wasn’t being chosen. I’ve felt like doing that before as well, spending afternoons cursing the developers at Microsoft that their product wouldn’t choose an index that I knew was a better choice.

    Over the years I’ve talked with the people that build the code behind the query optimizer and often it seems someone is submitting a bug in the way the QO/QP works. Most of the time, however, I find my respect growing for that team, and often find that the individual is falling victim to the “it works on my machine” syndrome. Too often someone is observing a single case, a single data set, and limited concurrency, all of which can drastically change the performance of a query on your system when they grow.

    SQL Server doesn’t have a perfect QP/QO system, but it has a very, very good one. Using too many hints almost feels like hard-coding a value in the system. There are times that it makes sense, but they are very rare.

    This post also reminds me that there are so many things to learn about SQL Server, and gaining a deeper understanding of how the internals of SQL Server work can pay off with much more efficient, and scalable code that handles your load as it grows.

    Steve Jones

    PS – This post makes me want to see Rob’s pre-conference session this October at the PASS Summit. Hopefully he will get picked and many of us will get the chance to learn more nuggets like this one.

  • Collation Conflicts in a SQL Server Join

    I went to run this query recently:

    select TOP 10 * 
     from users a
       inner join Banned b
       on a.username = b.username

    and got this lovely message.

    collation

    I’d seen that message before, so I knew what was wrong. The collations for the two tables were inconsistent. Since this was a database that was upgraded from another version of SQL, and uses objects from a third party, I wasn’t surprised that a specific collation was used. I had created the “b” table myself, using database defaults, and they didn’t match the object.

    I did a quick search since I couldn’t remember the exact syntax for the clause to add to my query. I ended up at a friend’s blog, Pinal Dave’s SQL Authority, and read this post: Cannot resolve collation conflict for equal to operation.

    The fix is easy, add a COLLATE DATABASE_DEFAULT to the join condition to force a specific collation on the field. I could easily have added a COLLATE Latin1_General_CI_AS as well, but since I knew that the second field was database defaults, I did this:

    select TOP 10 * 
     from users a
       inner join Banned b
       on a.username COLLATE DATABASE_DEFAULT = b.username

    Worked fine, and I was on my way.