
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
Making an existing field Unique in MySQL?
Unique in MySQL means we cannot add duplicate records. Let us now see how to create a unique constraint in the column at the time of creating a table.
mysql> create table UniqueConstDemo - > ( - > name varchar(100) unique - > ); Query OK, 0 rows affected (0.72 sec)
Now, we cannot have same value more than once for column ‘name’.
Inserting some records with duplicate values to check the error.
mysql> insert into UniqueConstDemo values('John'); Query OK, 1 row affected (0.19 sec) mysql> insert into UniqueConstDemo values('John');
On running the above query, the following error is visible.
mysql> insert into UniqueConstDemo values('John'); ERROR 1062 (23000): Duplicate entry 'John' for key 'name'
Inserting different values won’t give an error.
mysql> insert into UniqueConstDemo values('Bob'); Query OK, 1 row affected (0.11 sec)
Now, let us display all the 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)
- Related Articles
- How to make an existing field Unique in MySQL?
- How can we apply UNIQUE constraint to the field of an existing MySQL table?
- Which statement, other than ALTER TABLE statement, can be used to apply UNIQUE constraint to the field of an existing MySQL table?
- Making array unique in JavaScript
- How to add a random number between 30 and 300 to an existing field in MySQL?
- How to update field to add value to existing value in MySQL?
- How can we apply the PRIMARY KEY constraint to the field of an existing MySQL table?
- How can we add a FOREIGN KEY constraint to the field of an existing MySQL table?
- How add unique key to existing table (with non-unique rows)?
- How can we modify an existing MySQL event?
- How can we RENAME an existing MySQL event?
- Making a Pickle field in Django models
- How to rename a column in an existing MySQL table?
- Set NOT NULL attribute to an existing column in MySQL
- Adding characters in values for an existing int column in MySQL?

Advertisements