patternsqlMajor
Can I add a unique constraint that ignores existing violations?
Viewed 0 times
uniquecanignoresviolationsthatconstraintexistingadd
Problem
I have a table which currently has duplicate values in a column.
I cannot remove these erroneous duplicates but I would like to prevent additional non-unique values from being added.
Can I create a
I have tried using
In this case I have a table which ties licensing information to "CompanyName"
EDIT: Having multiple rows with the same "CompanyName" is bad data, but we can't remove or update those duplicates at this time. One approach is to have the
This data is queried by company name. For the few existing duplicates this will mean that multiple rows are returned and displayed... While this is wrong, it's acceptable in our use case. The goal is to prevent it in the future. It seems to me from the comments that I have to do this logic in the stored procedures.
I cannot remove these erroneous duplicates but I would like to prevent additional non-unique values from being added.
Can I create a
UNIQUE that doesn't check for existing compliance?I have tried using
NOCHECK but was unsuccessful.In this case I have a table which ties licensing information to "CompanyName"
EDIT: Having multiple rows with the same "CompanyName" is bad data, but we can't remove or update those duplicates at this time. One approach is to have the
INSERTs use a stored procedure which will fail for duplicates... If it was possible to have SQL check the uniqueness on its own, that would be preferable.This data is queried by company name. For the few existing duplicates this will mean that multiple rows are returned and displayed... While this is wrong, it's acceptable in our use case. The goal is to prevent it in the future. It seems to me from the comments that I have to do this logic in the stored procedures.
Solution
The answer is "yes". You can do this with a filtered index (see here for documentation).
For instance, you can do:
This creates a unique index, only on new rows, rather than on the old rows. This particular formulation would allow duplicates with existing values.
If you have just a handful of duplicates, you could do something like:
For instance, you can do:
create unique index t_col on t(col) where id > 1000;This creates a unique index, only on new rows, rather than on the old rows. This particular formulation would allow duplicates with existing values.
If you have just a handful of duplicates, you could do something like:
create unique index t_col on t(col) where id not in ();Code Snippets
create unique index t_col on t(col) where id > 1000;create unique index t_col on t(col) where id not in (<list of ids for duplicate values here>);Context
StackExchange Database Administrators Q#43823, answer score: 40
Revisions (0)
No revisions yet.