How do you add a unique constraint in MySQL?
In MySQL, you can add a unique constraint in two ways: 1. Using the UNIQUE keyword when creating a table. For example, the following is an example of adding a unique constraint when creating a table.
CREATE TABLE table_name (column1 datatype,
column2 datatype,
...
UNIQUE (column1, column2, ...)
);
In the example above, the parentheses after the UNIQUE keyword list the columns for which a unique constraint should be added. 2. Use the ALTER TABLE statement to add a unique constraint to an existing table. For example, here is an example of using the ALTER TABLE statement to add a unique constraint:
ALTER TABLE table_nameADD CONSTRAINT constraint_name UNIQUE (column1, column2, ...);
In the example above, the ALTER TABLE statement is used to modify an existing table, the ADD CONSTRAINT keyword is used to add constraints, the UNIQUE keyword followed by the columns listed in parentheses is used to add a unique constraint, and constraint_name is the name you specify for the constraint. Regardless of the method used, a unique constraint can be applied to one or more columns to ensure that the added values in the specified columns are unique.