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?
Advertisement
Answer
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”).