Introduction
A UNIQUE constraint makes sure that no two rows in a table have the same value in certain columns. It helps keep data clean and avoids duplicates.
CREATE TABLE table_name ( column_name datatype UNIQUE ); -- Or add UNIQUE constraint after table creation: ALTER TABLE table_name ADD UNIQUE (column_name);
CREATE TABLE users ( id INT PRIMARY KEY, email VARCHAR(100) UNIQUE );
ALTER TABLE products ADD UNIQUE (product_code);
CREATE TABLE employees ( id INT PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50), UNIQUE (first_name, last_name) );
CREATE TABLE customers ( customer_id INT PRIMARY KEY, phone VARCHAR(15) UNIQUE ); INSERT INTO customers (customer_id, phone) VALUES (1, '123-456-7890'); INSERT INTO customers (customer_id, phone) VALUES (2, '987-654-3210'); -- This next insert will fail because phone '123-456-7890' already exists INSERT INTO customers (customer_id, phone) VALUES (3, '123-456-7890');
UNIQUE constraint in MySQL?email in a table users?ADD UNIQUE (column_name) inside ALTER TABLE.users(id INT, username VARCHAR(50), email VARCHAR(100)) with a UNIQUE constraint on email, what happens if you run this query twice?INSERT INTO users (id, username, email) VALUES (1, 'alice', 'alice@example.com');
email prevents duplicate emails. The first insert adds the row successfully.CREATE TABLE products (id INT, code VARCHAR(20) UNIQUE);
INSERT INTO products VALUES (1, 'X123');
INSERT INTO products VALUES (2, 'X123');
code column has a UNIQUE constraint, so duplicate values like 'X123' are not allowed.code prevents duplicate values -> Option Afirst_name and last_name in a contacts table is unique, but each column alone can have duplicates. Which is the correct way to enforce this in MySQL?first_name, last_name) together correctly adds a UNIQUE constraint on the pair (first_name, last_name). Options B, C, and D enforce uniqueness incorrectly or partially.first_name, last_name) together -> Option CPass the test and this pattern moves unknown