The UNIQUE constraint in SQL is used to ensure that all values in a column (or a combination of columns) are unique across rows. It prevents duplicate values from being inserted into a column. The UNIQUE constraint can be applied to a single column or multiple columns (composite unique constraint).
Syntax:
CREATE TABLE table_name (
column1 datatype UNIQUE,
column2 datatype,
...
);
Example:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
email VARCHAR(255) UNIQUE,
name VARCHAR(100)
);
In this example, the email column must contain unique values. If an attempt is made to insert a duplicate email, it will result in an error.
Composite UNIQUE Constraint:
A unique constraint can also be applied to a combination of columns. This ensures that the combination of values in these columns is unique across all rows in the table.
CREATE TABLE orders (
order_id INT,
product_id INT,
order_date DATE,
UNIQUE (order_id, product_id)
);
Here, the combination of order_id and product_id must be unique, meaning that no two rows can have the same pair of values for these columns.
Notes:
- The
UNIQUEconstraint does not allowNULLvalues, but a column with aUNIQUEconstraint can still allow multipleNULLvalues (depending on the database system). - The
UNIQUEconstraint is similar to thePRIMARY KEYconstraint, but a table can have multipleUNIQUEconstraints, while it can only have onePRIMARY KEY.
No comments:
Post a Comment