
MySQL Unique Key
The MySQL unique key, also known as a unique constraint or unique index, is a database constraint that ensures the values in a specified column or set of columns are unique across all rows in a table. This means that no two rows can have the same values in the unique key column(s). Unique keys provide a way to enforce data integrity and prevent duplicate values in a table. Here’s how you can define a unique key in MySQL:
- Unique Key on a Single Column: To create a unique key on a single column, you can use the
UNIQUE
keyword when defining the column. For example:
CREATE TABLE your_table (
id INT PRIMARY KEY,
email VARCHAR(255) UNIQUE,
-- other columns
);
In this example, the email
column is defined as a unique key, which ensures that each email address in the table is unique.
- Unique Key on Multiple Columns: You can create a unique key on multiple columns by specifying the
UNIQUE
keyword for the group of columns. For example:
CREATE TABLE your_table (
id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
UNIQUE KEY (first_name, last_name),
-- other columns
);
In this example, the combination of first_name
and last_name
is unique, ensuring that no two rows can have the same first and last name.
- Adding a Unique Key to an Existing Table: You can add a unique key to an existing table using the
ALTER TABLE
statement. For example:
ALTER TABLE your_table
ADD UNIQUE KEY (column_name);
Replace your_table
with the name of your table and column_name
with the name of the column you want to make unique.
- Dropping a Unique Key: To remove a unique key from a table, you can use the
ALTER TABLE
statement with theDROP INDEX
clause. For example:
ALTER TABLE your_table
DROP INDEX index_name;
Replace your_table
with the table name and index_name
with the name of the unique key index.
Unique keys are useful for ensuring that specific columns or combinations of columns in a table contain unique values, which is essential for maintaining data integrity and preventing duplicate entries. When an attempt is made to insert or update data that violates the unique key constraint, MySQL will generate an error.