SQL Unique Constraints

In SQL, the UNIQUE constraint is used to ensure that each value in a column or a group of columns is unique. This constraint prevents duplicate values from being inserted into the table, which can help ensure data integrity.

Here is an example of how to create a UNIQUE constraint on a column:

CREATE TABLE customers (
    customer_id INT,
    customer_email VARCHAR(50) UNIQUE,
    customer_name VARCHAR(50)
);
Sou‮ww:ecr‬w.theitroad.com

In this example, the customer_email column is designated as UNIQUE. This means that each value in the customer_email column must be unique, and if a duplicate value is entered, an error will be returned.

You can also create a UNIQUE constraint on a group of columns. For example:

CREATE TABLE orders (
    order_id INT,
    customer_id INT,
    order_date DATE,
    UNIQUE (customer_id, order_date)
);

In this example, the UNIQUE constraint is created on the combination of customer_id and order_date. This means that each combination of values in these two columns must be unique.

You can add a UNIQUE constraint to an existing table using the ALTER TABLE command:

ALTER TABLE customers
ADD CONSTRAINT customer_email_unique UNIQUE (customer_email);

In this example, we are adding a UNIQUE constraint to the customer_email column of the customers table using the ALTER TABLE command.

By using the UNIQUE constraint, you can help ensure that data is entered correctly and prevent duplicate values from being stored in the table.