w3resource

How to Add a Unique Constraint to an SQL Column


Add a Unique Constraint

Write a SQL query to add a unique constraint to a column in an existing table.

Solution:

-- Add a unique constraint to the "Name" column to ensure no duplicate names.
ALTER TABLE Employees -- Specify the table to modify.
ADD CONSTRAINT UC_Name UNIQUE (Name); -- Ensure all names are unique.

Explanation:

    1. Purpose of the Query :

    1. The goal is to enforce uniqueness on the Name column in the Employees table by adding a unique constraint.
    2. b. This demonstrates how to use the ALTER TABLE statement to add constraints that maintain data integrity.

    2. Key Components :

    1. ALTER TABLE Employees : Specifies the table where the modification will occur.
    2. ADD CONSTRAINT UC_Name : Defines a named constraint (UC_Name) to enforce uniqueness.
    3. UNIQUE (Name) : Ensures that all values in the Name column are unique, preventing duplicate entries.

    3. Why use a Unique Constraint?

    1. A unique constraint ensures that no two rows in the table have the same value for the specified column.
    2. This is useful when you need to enforce business rules, such as ensuring that employee names are distinct.

    4. Real-World Application :

    1. For example, in a company database, you might want to prevent duplicate employee names to avoid confusion or errors in identifying employees.

Additional Notes:

  • Unique constraints are part of maintaining data integrity and preventing logical inconsistencies.
  • Sometimes unique constraints are critical, such as:
    • Preventing duplicate entries in key columns like usernames, email addresses, or product codes.
    • Supporting indexing and query optimization by ensuring uniqueness.

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous SQL Exercise: How to Drop a Column from an SQL Table.
Next SQL Exercise: How to Add a Foreign Key in SQL to Link Tables.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.