How to set a unique index in MySQL?

In MySQL, you can use the UNIQUE keyword to set a unique index.

When creating a table, you can use the UNIQUE keyword in the column definition to set a unique index, for example:

CREATE TABLE mytable (
    id INT PRIMARY KEY,
    name VARCHAR(50),
    UNIQUE (name)
);

In the mentioned example, the name column is set as a unique index to ensure that the values in the name column are unique in the table.

Moreover, you can also utilize the ALTER TABLE statement to add a unique index, for example:

ALTER TABLE mytable ADD UNIQUE (name);

In the above example, a unique index named “name” was added to the existing table called mytable.

It should be noted that a unique index does not allow duplicate values. If attempting to insert or update data violates the rules of a unique index, MySQL will throw an error. You can use the INSERT IGNORE or UPDATE IGNORE statements to ignore these errors, but doing so will result in the insert or update operation not being executed.

bannerAds