SQL UNIQUE Constraint on Multiple Columns
SQL UNIQUE Constraint on Multiple Columns is a SQL statement in the Constraints category. A composite UNIQUE constraint ensures the combination of values across columns is unique. The syntax is CONSTRAINT uq_name UNIQUE (col1, col2). It returns composite unique constraint. A typical example: CREATE TABLE product_variants ( id INT PRIMARY KEY, product_id INT, size VARCHAR(10), color VARCHAR(20), CONSTRAINT uq_product_variant UNIQUE (product_id, size, color) ); -- These inserts work (different combinations): INSERT INTO product_variants VALUES (1, 100, 'M', 'Red'); INSERT INTO product_variants VALUES (2, 100, 'M', 'Blue'); -- OK: same size, diff color INSERT INTO product_variants VALUES (3, 100, 'L', 'Red'); -- OK: same color, diff size -- This fails (duplicate combination): INSERT INTO… A close relative is PRIMARY KEY, which a column or set of columns that uniquely identifies each row. Only one PK per table. Automatically creates a unique index. A close relative is FOREIGN KEY, which ensures referential integrity: values in this column must exist in the referenced parent table.