What is the purpose of a UNIQUE constraint in SQL?
a) To ensure that all values in a column are different
b) To allow only NULL values in a column
c) To prevent any changes to the column after insertion
d) To allow duplicate values in a table
Answer:
a) To ensure that all values in a column are different
Explanation:
The UNIQUE constraint ensures that all values in a column or a set of columns are distinct across rows, meaning no two rows can have the same value in the constrained column(s).
For example, a UNIQUE constraint on an email column ensures that no two users can have the same email address in a users table. This is useful for enforcing data integrity where duplicate values would cause issues.
UNIQUE constraints can be applied to one or more columns, and a table can have multiple UNIQUE constraints in addition to its primary key.