Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add special constraint to avoid duplicate rows with this condition?

I have a table that looks like this:

ClientId  FloorNum   BedNum   IsActive
11        2          212      1        
12        2          214      0        
12        2          214      1        
13        2          215      0        
13        2          215      0        
13        2          215      0        
13        2          215      0        
13        2          215      1        
12        2          215      1        

As you can see, FloorNum/BedNum combination 2/215 has two rows where IsActive equals 1. This cannot happen.

On the other hand, one FloorNum/BedNum combination can have many rows where IsActive equals 0.

How can I add a constraint to a table so that a FloorNum/BedNum combination can only have one row where IsActive = 1?

Any help is appreciated.

like image 290
fdkgfosfskjdlsjdlkfsf Avatar asked Apr 18 '16 14:04

fdkgfosfskjdlsjdlkfsf


People also ask

Which constraints will prevent the entry of duplicate rows?

Primary Key will prevent the entry of duplicate rows.

How do I restrict duplicate rows in SQL?

In the Navigation Pane, right-click the table that contains the field, and then click Design View. Select the field that you want to make sure has unique values. In the Field Properties pane at the bottom of the table design view, on the General tab, set the Indexed property to Yes (No duplicates).

What type of constraint is used to prevent duplicate values in a field?

A unique constraint (also referred to as a unique key constraint) is a rule that forbids duplicate values in one or more columns within a table. Unique and primary keys are the supported unique constraints.


1 Answers

You can create a filtered unique index with a WHERE clause.

CREATE UNIQUE NONCLUSTERED INDEX IX_[index name]_FloorNum_BedNum ON [myTable] (
    FloorNum ASC,
    BedNum ASC)
WHERE (IsActive = 1)

This will only take into account records where the IsActive column is set to 1.

Based on your description I think that ClientId is not necessary in this example but if I am wrong you can add it to the index as well.

like image 168
Igor Avatar answered Sep 21 '22 15:09

Igor