MySQL UNIQUE Constraint
MySQL UNIQUE Constraint
The UNIQUE constraint in MySQL ensures that all values in a column are distinct.
It is used to prevent duplicate values in a column while allowing NULL values (except in some versions where only one NULL is allowed).
🔹 Syntax (During Table Creation)
-
Can be applied to single or multiple columns.
-
Can also define table-level UNIQUE constraint for multiple columns.
🔹 Syntax (Using ALTER TABLE)
-
Adds a
UNIQUEconstraint to an existing column.
🔹 Example 1: Unique Column
-
emailcolumn must have unique values; duplicates are not allowed.
🔹 Example 2: Table-Level UNIQUE Constraint (Multiple Columns)
-
Combination of
first_name+last_namemust be unique. -
Two employees can have the same first name or last name individually, but not the same combination.
🔹 Example 3: Adding UNIQUE to Existing Column
-
Ensures that
usernamevalues are unique.
🔹 Key Points
-
UNIQUE ensures distinct values in a column or a set of columns.
-
Multiple UNIQUE constraints can exist in a table.
-
Allows NULL values, but duplicate non-NULL values are not allowed.
-
Often used for emails, usernames, or IDs to avoid duplicates.
-
Can be applied during table creation or added later using
ALTER TABLE.
