unique Constraint doesn't work properly with space character

Ates Ates 21 Reputation points
2022-06-29T07:13:59.803+00:00

In char data type including unique constraints, when adding a space starting to the string in the column, unique constraint violated error is given. For example, when trying to make a column with '10200 - Kopie' '10200 - Kopie - Kopie' I get a unique constraints error, although it is clear that the two data are not the same. SQL Server 2019.

Developer technologies Transact-SQL
SQL Server Other
{count} votes

Accepted answer
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2022-06-29T21:59:23.92+00:00

    As other have said, the data you posted does not result in any constraint violation:

       CREATE TABLE Ates (col varchar(200) NOT NULL UNIQUE)  
       go  
       INSERT Ates(col)  
          VALUES('10200 - Kopie'),   
                 ('10200 - Kopie - Kopie')  
       go  
    

    yields (2 rows affected).

    However, if now attempt to add:

       INSERT Ates(col)  
          VALUES('10200 - Kopie   ')  
    

    This does indeed result in a constraint violation. In SQL Server trailing spaces does not count as significant when comparing values.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. LiHong-MSFT 10,056 Reputation points
    2022-06-30T02:11:16.073+00:00

    Hi @Ates Ates
    Could you please share us your table structure (CREATE TABLE …)?
    Since I guess it may be caused by the short length of your CHAR column, please refer to the following example.

    CREATE TABLE Test (col char(13) NOT NULL UNIQUE)  
      
    SET ANSI_WARNINGS OFF;  
    INSERT Test(col)  
    VALUES('10200 - Kopie'),   
          ('10200 - Kopie - Kopie')  
    SET ANSI_WARNINGS ON;  
      
    DROP TABLE Test  
    

    Of course, this is just my guess. Whether it is correct or not depends on your table structure.

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.