0

I am using SQL Server. I have this table:

CREATE TABLE Student
(
   ID int PRIMARY KEY,
   FirstName varchar(100),
   LastName varchar(100),
   Active bit;
)

I want to have unique(FirstName, LastName) students only if Active = 1. If they are inactive, unique constraint should not trigger. Any idea?

2
  • 2
    This is a bad idea. What if a duplicated user become active again? What about homonyms? Commented Jan 18, 2019 at 10:02
  • @Cid this is just an example to keep it simple the real problem. Commented Jan 18, 2019 at 10:03

2 Answers 2

6

You can't create a CONSTRAINT for that, however, you can create a filtered unique index:

USE Sandbox;
GO

CREATE TABLE dbo.Student (ID int IDENTITY(1, 1) PRIMARY KEY,
                          FirstName varchar(100),
                          LastName varchar(100),
                          Active bit);


CREATE UNIQUE INDEX UQ_StudentName
    ON Student (FirstName,LastName)
    WHERE Active = 1;
GO

INSERT INTO dbo.Student (FirstName,
                         LastName,
                         Active)
VALUES ('Jane', 'Smith', 1); --Success
GO
INSERT INTO dbo.Student (FirstName,
                         LastName,
                         Active)
VALUES ('Jane', 'Smith', 0); --Success
GO
INSERT INTO dbo.Student (FirstName,
                         LastName,
                         Active)
VALUES ('Jane', 'Smith', 0); --Success
GO
INSERT INTO dbo.Student (FirstName,
                         LastName,
                         Active)
VALUES ('Jane', 'Smith', 1); --Fails;
GO

UPDATE dbo.Student
SET Active = 1
WHERE ID = 2; --Fails;
GO

SELECT *
FROM dbo.Student;
GO

DROP TABLE dbo.Student;

I however, highly recommend against the thought that names are unique. I (personally) shared my name and date of birth with another person at several places in my youth and businesses that treated names (and date of birth) as unique on their systems were such a head ache for the both of us (there really were places where I (or they) couldn't register without using an abbreviated name because we "already existed").

Sign up to request clarification or add additional context in comments.

1 Comment

prefect solution, thank you. I agree that names can't be unique, but that was just an simplified example to help me solve my real problem .
3

Create a filtered unique index:

CREATE UNIQUE INDEX UNI_Student_FirstName_LastName ON Student (FirstName, LastName)
WHERE Active = 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.