Search code examples
sqlsql-servercheck-constraints

Is it possible to have an equality constraint in SQL?


I have the following:

create table dbo.Users
(
  Id int identity not null 
    constraint PK_Users_Id primary key clustered (Id),  
  Email nvarchar (120) not null
    constraint UQ_Users_Email unique (Email),
  Username nvarchar (120) not null
    constraint UQ_Users_Username unique (Username)
);

Can I set a constraint to make Email and Username equal?

Thank You, Miguel


Solution

  • Below is the appropriate SQL to address the question directly:

    create table dbo.Users
    (
      Id int identity not null 
        constraint PK_Users_Id primary key clustered (Id),  
      Email nvarchar (120) not null
        constraint UQ_Users_Email unique (Email),
      Username nvarchar (120) not null
        constraint UQ_Users_Username unique (Username)      
    );
    
    
    alter table dbo.Users add constraint CK_EmailEqualsUsername
    check (username = email)
    

    A, most likely better, more common approach would be to perform the comparison somewhere higher in the call stack (different layer e.g.: Presentation Layer/Domain Layer/Service Layer)