Unique constraint prevents duplicates and ensures that there is only one distinct value of their own in a column. Perhaps, the most widely used constraint in a database to maintain data integrity is Primary key. Though, practically a table can have only one primary key. Therefore, to enforce further uniqueness in other columns we use Unique key constraint.
We can have multiple unique constraints in a table compared to one primary key. When we create a unique constraint on a column or group of columns, SQL server validates that a column will not have a single value repeated twice. In case you forcefully try to insert a duplicate value, SQL Server will raise a Unique constraint violation error.
Unique Constraints – Points to Remember
1. A table can have multiple unique constraints rather than having one primary key.
2. Unique constraints can be created on multiple columns to maintain uniqueness likewise composite primary key.
3. Unique constraint will allow having a single NULL value in a table.
4. SQL Server adds a Unique Non-Clustered Index on a column having Unique constraint favouring faster result retrieval using Index.
Comparing Unique Constraint to Primary Key Constraint
1. Primary key constraint restricts usages of NULL values whereas Unique Constraint allows a
single NULL value.
2. By default SQL Server allows multiple Unique constraints per table whereas a single primary
key constraint can be created per table.
3. SQL Server adds a Unique Clustered index with primary key and Unique Non-clustered index with
Unique constraint by default.
Creating Unique Constraints On Single Column
Let’s walk through with few examples on how to use Unique constraints to enforce uniqueness in a table having a primary key.
The following query creates a Country(CountryCode, Name, Population) table. Including a primary key on CountryCode column and unique constraint on Name column. Enforcing a rule to have Unique country names in a table along with unique Country codes. Notice that NOT NULL constraint added to Name column avoiding any NULL values.
Always a good habit to name your constraint with friendly names like UK_Country_Name for Unique constraint instead of allowing SQL Server to create a one with random and non-readable names. The following query first creates a Country table and Inserts 3 rows successfully.
Unique Constraint Violation Error
While trying to insert the 4th row, we have intentionally added unique countrycode along with the duplicate name “India”, therefore resulting in a violation of unique key constraint causing an error.
Msg 2627, Level 14, State 1, Line 25
Violation of UNIQUE KEY constraint ‘UK_Country_Name’. Cannot insert duplicate key in object ‘dbo.Country’. The duplicate key value is (India). The statement has been terminated.
Creating Unique Constraints On Multiple Column
In the above example, we had created a unique constraint on a single column to enforce uniqueness. However, it’s possible to add a unique constraint on multiple columns.
In the following query, we have created Player (Name, Trophy) table. Alongside, adding a unique constraint on the combination of Name and Trophy columns to have a composite unique constraint. SQL Server will validate that values are always unique in the combination of two columns instead of one.
Referring to the values we can notice that “Federer”, “Aus Open” and “Federer”, “US Open” is allowed. However, “Federer”, “US Open” is considered as duplicate violating the composite unique constraint rule.
Creating Unique Constraints On Existing Table
In the following example, we are creating a unique constraint on an existing table which already has a primary key constraint and 3 rows. Let’s reuse the Country table from the first example. Create Country (CountryCode, Name, Population) having a primary key on CountryCode column.
Adding a unique constraint later using ALTER TABLE statement. Pay careful attention, if the existing table has duplicate values in a column, before adding a unique constraint, as duplicate values won’t allow a unique constraint to be added on that column resulting in a violation of a rule.
Dropping Unique Constraints
The following query shows using DROP statement to remove a Unique constraint on a table. Before we remove a unique constraint, best practice to check if a constraint exists then drop it else ignore the DROP statement.
Comparing Unique Constraint to Unique Index
Perhaps, it’s vital to understand the primary difference between Unique constraint and Unique Indexes in SQL Server. Essentially both options enforce uniqueness on a column. However, we can use both of them interchangeably as per database design and needs.
1. Unique constraint and Unique index both enforce uniqueness on a column.
2. If our primary requirement is to add a Unique index on a column with a goal to enable faster results. Adding unique index also gives us the opportunity to INCLUDE non-indexed columns or add a filtered unique index which is not possible while adding the unique constraint.
3. Under the hood, Unique constraint adds a non-clustered unique index after creating a unique constraint on a column, but we are not allowed to INCLUDE any non-indexed columns or modify it to create a filter index.
4. We can’t disable a unique constraint. Although it’s allowed to disable a unique index when needed.
In this tech-recipes post we have learned the use of Unique constraint in SQL Server to enforce uniquiness in a table when a primary key is already been added. Adding a Unique constraint in existing table, adding composite unique constraint and dropping it. If you like this post you may browse through Tech-Recipes Database Archive posts to learn more useful stuff.