Thursday, December 19, 2024

SQL UNIQUE Keyword

 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 UNIQUE constraints, but each constraint applies to different columns or sets of columns.
  • UNIQUE constraints allow NULL values unless the column is defined as NOT NULL. However, the NULL values are treated as distinct, so you can have multiple rows with NULL values in a column with a UNIQUE constraint.

No comments:

Post a Comment