Home >Database >Mysql Tutorial >How Can Filtered Indexes Enforce Conditional Unique Constraints in SQL Server?
Conditional Unique Constraints with Filtered Indexes in SQL Server
Database design sometimes requires conditional unique constraints: uniqueness enforced on a column set only when another column meets a specific condition. This is common when managing active and inactive records, preserving data integrity. SQL Server's filtered indexes offer an efficient solution. A filtered index creates a unique index on a table's subset of rows, defined by a filter predicate.
Implementing Uniqueness Based on Record Status
Imagine a table with ID
, Name
, and RecordStatus
columns. We need a unique constraint on (ID
, RecordStatus
) only when RecordStatus = 1
(active records). A filtered index achieves this:
<code class="language-sql">CREATE UNIQUE INDEX MyIndex ON MyTable (ID) WHERE RecordStatus = 1;</code>
This ensures uniqueness for ID
only when RecordStatus
is 1, allowing multiple inactive (RecordStatus = 2
) records with the same ID
.
Beyond Record Status: Versatile Conditional Uniqueness
Filtered indexes aren't limited to record status. They enable granular control over data uniqueness based on various criteria, enhancing data integrity and performance.
Advantages of Filtered Indexes
Compared to alternatives like triggers, filtered indexes offer:
Summary
SQL Server's filtered indexes provide a robust and efficient way to enforce conditional unique constraints. They offer a balance between data integrity, performance, and storage optimization.
The above is the detailed content of How Can Filtered Indexes Enforce Conditional Unique Constraints in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!