Introduction
A unique index helps keep data clean by making sure no two rows have the same value in certain columns.
CREATE UNIQUE INDEX index_name ON table_name (column1, column2, ...);
CREATE UNIQUE INDEX idx_email ON users (email);
CREATE UNIQUE INDEX idx_product_code ON products (product_code);
CREATE UNIQUE INDEX idx_user_fullname ON users (first_name, last_name);
CREATE TABLE employees ( id INT PRIMARY KEY, email VARCHAR(100) ); CREATE UNIQUE INDEX idx_email ON employees (email); INSERT INTO employees (id, email) VALUES (1, 'alice@example.com'); INSERT INTO employees (id, email) VALUES (2, 'bob@example.com'); -- This next insert will fail because the email is already used INSERT INTO employees (id, email) VALUES (3, 'alice@example.com');
UNIQUE index in a database table?email in a table named users?products with a unique index on sku, what happens when you run this SQL?INSERT INTO products (sku, name) VALUES ('A123', 'Item1');
INSERT INTO products (sku, name) VALUES ('A123', 'Item2');sku means no two rows can have the same sku value.username column. The following query causes an error:INSERT INTO users (username) VALUES ('john');
INSERT INTO users (username) VALUES ('john');employees with a unique index on (email, department_id). Which of these inserts will cause a unique index violation if the table already has a row with email='alice@example.com' and department_id=10?Pass the test and this pattern moves unknown