Home > Database > Mysql Tutorial > How to Enforce Unique Constraints Across Multiple Columns in MySQL?

How to Enforce Unique Constraints Across Multiple Columns in MySQL?

Susan Sarandon
Release: 2024-12-16 16:37:10
Original
386 people have browsed it

How to Enforce Unique Constraints Across Multiple Columns in MySQL?

Specifying Unique Constraints for Multiple MySQL Columns

In the context of MySQL database management, a table's unique constraint ensures that no two rows contain identical values for a specified set of columns. To enforce such a constraint, we utilize the ALTER TABLE and ADD UNIQUE commands in conjunction.

Synopsis:

ALTER TABLE <table_name> ADD UNIQUE <index_name>(<column1>, <column2>, ...)
Copy after login

Example:

Consider the following table schema:

table votes (
    id,
    user,
    email,
    address,
    primary key(id),
);
Copy after login

To ensure that the combination of user, email, and address columns is unique, we can execute the following command:

ALTER TABLE `votes` ADD UNIQUE `unique_index`(`user`, `email`, `address`);
Copy after login

Explanation:

  • The ALTER TABLE statement modifies the table's schema by adding a unique constraint.
  • The ADD UNIQUE clause specifies that the specified columns (user, email, address) must have unique values across all rows.
  • The unique_index is a custom name assigned to the index.

By implementing this constraint, MySQL guarantees that there cannot be multiple rows with identical user, email, and address combinations, preventing duplicate entries.

The above is the detailed content of How to Enforce Unique Constraints Across Multiple Columns in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template