Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow a Boolean index only be unique for True

I have a table that I'm doing logical deletes on. I have a column Name and a column Is_Active. Name is a varchar and Is_active is a bool.

I can't make Name unique because there will be multiple rows that have the same name. Where Is_Active == False.

I need to make sure that at any time there is only one record for a Name where Is_Active == True.

Is there a way I can do this ? Or can anybody suggest a better way ?

like image 988
Jeff Finn Avatar asked Apr 20 '15 14:04

Jeff Finn


People also ask

How do you create a unique index?

Right-click the table on which you want to create a unique index and select Design. On the Table Designer menu, select Indexes/Keys. In the Indexes/Keys dialog box, click Add. Select the new index in the Selected Primary/Unique Key or Index text box.

What is an unique index?

Unique indexes are indexes that help maintain data integrity by ensuring that no rows of data in a table have identical key values. When you create a unique index for an existing table with data, values in the columns or expressions that comprise the index key are checked for uniqueness.

How do you use boolean index in Python?

In its simplest form, boolean indexing behaves as follows: Suppose x is an -dimensional array, and ind is a boolean-value array of the same shape as x . Then x[ind] returns a 1-dimensional array, which is formed by traversing x and ind using row-major ordering.

What is boolean indexing explain with example?

Boolean indexing helps us to select the data from the DataFrames using a boolean vector. We need a DataFrame with a boolean index to use the boolean indexing. Let's see how to achieve the boolean indexing. Create a dictionary of data. Convert it into a DataFrame object with a boolean index as a vector.


2 Answers

You can create a unique filtered index at database level:

CREATE UNIQUE INDEX UQ_EmployeeName
ON Employee (Name)
WHERE Is_Active = 1

The above index will not allow duplicate records like ('Bob', 1). It will allow though records like ('Bob', 1), ('Bob', 0) to co-exist in your database.

like image 50
Giorgos Betsos Avatar answered Nov 15 '22 10:11

Giorgos Betsos


Allow a Filtered Index having condition of "not being 0". 0 representing false. This way, only one true value can exist. You won't have to create nullable column, just ignore the false value using filter.

Example of EF Core:

entity.HasIndex(x => new {x.ArticleId, x.IsActive}).IsUnique().HasFilter("[IsActive] != 0");

It's not a workaround so I love it!

like image 40
Imran Faruqi Avatar answered Nov 15 '22 08:11

Imran Faruqi