The UNIQUE
constraint ensures that all values in a column (or group of columns) are distinctโno duplicates allowed.
Itโs perfect for fields like usernames, emails, or any data that must be unique.
column_name data_type UNIQUE -- or for multi-column: UNIQUE (column1, column2)
CREATE TABLE users ( user_id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL UNIQUE, email VARCHAR(100) UNIQUE, phone VARCHAR(20) ); -- Multi-column unique key (e.g., one user canโt have same phone+email) CREATE TABLE contacts ( id INT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(100), phone VARCHAR(20), UNIQUE (email, phone) );
ALTER TABLE users ADD CONSTRAINT uq_username UNIQUE (username);
ALTER TABLE users DROP INDEX uq_username;
SELECT column, COUNT(*) FROM table GROUP BY column HAVING COUNT(*) > 1;
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!