The UNIQUE
constraint in SQL is used to ensure that all values in a column are different from each other. It prevents duplicate values in the specified column(s) of a table.
The basic syntax for adding a UNIQUE
constraint is:
CREATE TABLE table_name (
column1 datatype UNIQUE,
column2 datatype,
...
);
Here’s an example of creating a table with a UNIQUE
constraint:
CREATE TABLE Users (
UserID INT PRIMARY KEY,
Username VARCHAR(50) UNIQUE,
Email VARCHAR(100) UNIQUE
);
This ensures that both the Username
and Email
fields cannot have duplicate values across the table.
If you need to add a UNIQUE
constraint to an existing column, you can use the following command:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (column_name);
For example:
ALTER TABLE Users
ADD CONSTRAINT unique_email UNIQUE (Email);
When using the UNIQUE
constraint, keep in mind:
UNIQUE
constraints, but only one primary key.UNIQUE
constraint, which will result in errors.