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 ?
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.
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.
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With