Set a unique constraint across multiple table columns

Jot*_*oth 0 sql-server database-design unique-constraint

I am creating a table in SQL Server with the following columns:

ic_card_num, 
employee_id, 
active
Run Code Online (Sandbox Code Playgroud)

multiple duplicates of ic_card_num and active are okay if only one card is active:

employee_id | ic_card_num |  active       
   123      |    111      |   false      
   235      |    111      |   true      
   987      |    111      |   false      
Run Code Online (Sandbox Code Playgroud)

I want to avoid this:

employee_id | ic_card_num |  active       
   123      |    111      |   true      
   235      |    111      |   true      
   987      |    111      |   false      
Run Code Online (Sandbox Code Playgroud)

I am working with SQL Server, is there a way to ensure that I don't allow more than one active id_card_num record in my table?

Dav*_*oft 5

Use a unique filtered index:

create table ct
(
  ic_card_num int,
  employee_id int,
  active bit
)

create unique index ak_OnlyOneActive_ic_card 
on ct(ic_card_num) 
where active = 1

insert into ct(employee_id, ic_card_num, active)
values (123,111,1),(978,111,0)
go

insert into ct(employee_id, ic_card_num, active)
values (235,111,1)
--Cannot insert duplicate key row in object 'dbo.ct' with unique index 'ak_OnlyOneActive_ic_card'. The duplicate key value is (111).
Run Code Online (Sandbox Code Playgroud)