How to set up a unique constraint in MySQL?
In MySQL, you can set a uniqueness constraint by using the UNIQUE keyword. This constraint ensures that the values in a specific column or group of columns within a table are unique.
Here are several ways to set a uniqueness constraint in MySQL:
When creating a table, you can set a uniqueness constraint by using the UNIQUE keyword after defining the columns. For example, the following example sets a uniqueness constraint for the name column when creating a table.
CREATE TABLE my_table (
id INT PRIMARY KEY,
name VARCHAR(50) UNIQUE,
...
);
2. Implementing a unique constraint using the ALTER TABLE statement: You can add a unique constraint using the ALTER TABLE statement. For instance, the following example adds a unique constraint to the name column in an existing table.
ALTER TABLE my_table
ADD CONSTRAINT unique_name UNIQUE (name);
3. Creating a unique index is another way to set uniqueness constraints. A unique index can ensure that the values in a column or group of columns in a table are unique. For example, the following example creates a unique index for the ‘name’ column using the CREATE INDEX statement:
CREATE UNIQUE INDEX idx_name ON my_table (name);
Regardless of the method used, uniqueness constraints ensure that the values in the specified column or columns combination in a table are unique. If an attempt is made to insert or update a record with duplicate values, an error will be triggered.