MySQL UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are unique, preventing duplicate values. You can apply it to one or more columns.
Example with Tamil Kings
CREATE TABLE tamil_kings_unique (
id INT AUTO_INCREMENT PRIMARY KEY,
king_name VARCHAR(100) UNIQUE,
reign_period VARCHAR(50)
);
Code Explanation: The king_name column must contain unique values, ensuring that no two kings in the tamil_kings_unique table have the same name.
Best Practices
- Use
UNIQUEfor columns that require distinct values, like usernames or email addresses. - Consider using composite unique keys for columns that require combined uniqueness.
Key Takeaways
- The
UNIQUEconstraint ensures data uniqueness within a column. - Multiple unique columns can be defined in a single table.