The UNIQUE keyword in SQL is used to ensure that all values in a column or a set of columns are distinct. When a column is defined with the UNIQUE constraint, it enforces that no two rows can have the same value for that column (or combination of columns).
Syntax:
CREATE TABLE table_name (
column1 datatype UNIQUE,
column2 datatype,
...
);
Or, for multiple columns:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
UNIQUE (column1, column2)
);
Example 1: Single column with UNIQUE
CREATE TABLE Employees (
ID INT PRIMARY KEY,
Name VARCHAR(100),
Email VARCHAR(100) UNIQUE
);
In this example, the Email column must have unique values for each row in the Employees table.
Example 2: Multiple columns with UNIQUE
CREATE TABLE Orders (
OrderID INT,
CustomerID INT,
ProductID INT,
UNIQUE (CustomerID, ProductID)
);
In this example, the combination of CustomerID and ProductID must be unique, but each column individually can have duplicate values.
Key Points:
- A table can have multiple
UNIQUEconstraints, but each constraint applies to different columns or sets of columns. UNIQUEconstraints allowNULLvalues unless the column is defined asNOT NULL. However, theNULLvalues are treated as distinct, so you can have multiple rows withNULLvalues in a column with aUNIQUEconstraint.
No comments:
Post a Comment