Home > Database > Mysql Tutorial > body text

Make existing field unique in MySQL?

PHPz
Release: 2023-09-15 15:29:09
forward
1360 people have browsed it

在 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)
Copy after login

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');
Copy after login

When running the above query, the following error occurs.

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

No errors in inserting different values.

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

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

mysql> select *from UniqueConstDemo;
Copy after login

The following is the output.

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

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!

source:tutorialspoint.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!