Languages
[Edit]
EN

MySQL - make column values unique

0 points
Created by:
Marcino
720

In this article, we would like to show you how to make column values unique in MySQL.

In MySQL we can create unique constraint for single or multiple columns.

Quick solution:

ALTER TABLE `table_name` 
ADD UNIQUE (`column_name`);

or:

ALTER TABLE `table_name`
ADD CONSTRAINT `constraint_name` UNIQUE (`column_name`);

or:

ALTER TABLE `table_name`
ADD CONSTRAINT `constraint_name` UNIQUE (`column1`, `column2`, `columnN`);

 

Practical example

To show how to make column values unique, we will use the following table:

MySQL - example data used to make column values unique
MySQL - example data used to make column values unique

Example 1 - make single column unique

In this example, we will make name column unique.

Query:

ALTER TABLE `users`
ADD CONSTRAINT `UC_username` UNIQUE (`name`);

Result:

Using query

SHOW INDEXES FROM `users`;
MySQL - make column value unique - result
MySQL - make column value unique - result

Using HeidiSQL

MySQL - make column value unique - result 
MySQL - make column value unique - result

Example 2 - make multiple columns unique

In this example, we will make name and country columns unique.

Query:

ALTER TABLE `users`
ADD CONSTRAINT `UC_user` UNIQUE (`name`, `country`);

Result:

Using query

SHOW INDEXES FROM `users`;
MySQL - make multiple column values unique - result
MySQL - make multiple column values unique - result 

Using HeidiSQL:

MySQL - make multiple column values unique - result
MySQL - make multiple column values unique - result 
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

MySQL - Problems

MySQL - make column values unique
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join