Junior — Middle
Could you explain what the UNIQUE constraint in SQL means and how it works?
sobes.tech AI
Answer from AI
The UNIQUE constraint in SQL guarantees that all values in a column (or a set of columns) are unique, meaning there will be no duplicate values.
This constraint is used to ensure data integrity, for example, to prevent duplicates in a table based on a specific field.
Example of creating a table with a UNIQUE constraint:
CREATE TABLE Users (
ID INT PRIMARY KEY,
Email VARCHAR(255) UNIQUE
);
In this example, the Email column cannot have two identical values. If you try to insert a duplicate email, the database will throw an error.
You can also create unique constraints on multiple columns to ensure that the combination of values is unique.