Wednesday, 27 November 2019

Using MySQL UNIQUE Index To Prevent Duplicates

Summary: in this tutorial, you will learn how to use the MySQL UNIQUE index to prevent duplicate values in one or more columns in a table.

Introduction to the MySQL UNIQUE index

To enforce the uniqueness value of one or more columns, you often use the PRIMARY KEY constraint. However, each table can have only one primary key. Hence, if you want to have a more than one column or a set of columns with unique values, you cannot use the primary key constraint.
Luckily, MySQL provides another kind of index called UNIQUE index that allows you to enforce the uniqueness of values in one or more columns. Unlike the PRIMARY KEY index, you can have more than one UNIQUE index per table.
To create a UNIQUE index, you use the CREATE UNIQUE INDEX statement as follows:
Another way to enforce the uniqueness of value in one or more columns is to use the UNIQUE constraint.
When you create a UNIQUE constraint, MySQL creates a UNIQUE index behind the scenes.
The following statement illustrates how to create a unique constraint when you create a table.
In this statement, you can also use the UNIQUE INDEX instead of the UNIQUE KEY because they are synonyms.
If you want to add a unique constraint to an existing table, you can use the ALTER TABLE statement as follows:

MySQL UNIQUE Index & NULL

Unlike other database systems, MySQL considers NULL values as distinct values. Therefore, you can have multiple NULL values in the UNIQUE index.
This is how MySQL was designed. It is not a bug even though it was reported as a bug.
Another important point is that the UNIQUE constraint does not apply to NULL values except for the BDB storage engine.

MySQL UNIQUE index examples

Suppose, you want to manage contacts in an application. You also want that email of every contact in the contacts table must be unique.
To enforce this rule, you create a unique constraint in the CREATE TABLE statement as follows:
If you use the SHOW INDEXES statement, you will see that MySQL created a UNIQUE index for email column.
MySQL UNIQUE Constraint Example
Let’s insert a row into the contacts table.
Now if you try to insert a row whose email is john.doe@mysqltutorial.org, you will get an error message.
Suppose you want the combination of first_namelast_name, and  phone is also unique among contacts. In this case, you use the CREATE INDEX statement to create a UNIQUE index for those columns as follows:
Adding the following row into the contacts table causes an error because the combination of the first_namelast_name, and phone already exists.
In this tutorial, you have learned how to use the MySQL UNIQUE index to prevent duplicate values in the database.

0 comments:

Post a Comment