insertintoUniqueConstDemovalues('Joh"/> insertintoUniqueConstDemovalues('Joh">

Home  >  Article  >  Database  >  Make existing field unique in MySQL?

Make existing field unique in MySQL?

PHPz
PHPzforward
2023-09-15 15:29:091361browse

在 MySQL 中使现有字段唯一?

Uniqueness in MySQL means that we cannot add duplicate records. Now let us see how to create a unique constraint in a column while creating a table.

mysql> create table UniqueConstDemo
- > (
- > name varchar(100) unique
- > );
Query OK, 0 rows affected (0.72 sec)

Now, we cannot use the same value multiple times in the "name" column.

Insert some records with duplicate values ​​to check for errors.

mysql> insert into UniqueConstDemo values('John');
Query OK, 1 row affected (0.19 sec)

mysql> insert into UniqueConstDemo values('John');

When running the above query, the following error occurs.

mysql> insert into UniqueConstDemo values('John');
ERROR 1062 (23000): Duplicate entry 'John' for key 'name'

No errors in inserting different values.

mysql> insert into UniqueConstDemo values('Bob');
Query OK, 1 row affected (0.11 sec)

Now, let us display all records with the help of SELECT statement.

mysql> select *from UniqueConstDemo;

The following is the output.

+-------+
| name  |
+-------+
| Bob   |
| John  |
+-------+
3 rows in set (0.00 sec)

The above is the detailed content of Make existing field unique in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete