- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MySQL UNIQUE declaration to avoid inserting duplicate values?
Following is the declaration for a UNIQUE clause in MySQL −
create table yourTableName ( yourColumnName1 dataType, yourColumnName2 dataType, UNIQUE(yourColumnName1), UNIQUE(yourColumnName1) );
Let us first create a table −
mysql> create table DemoTable ( Value int, Value2 int, UNIQUE(Value), UNIQUE(Value2) ); Query OK, 0 rows affected (13.98 sec)
Insert some records in the table using insert command. Here, duplicate records won’t insert because we have used UNIQUE above −
mysql> insert into DemoTable values(10,20) ; Query OK, 1 row affected (0.32 sec) mysql> insert into DemoTable values(10,30); ERROR 1062 (23000): Duplicate entry '10' for key 'Value' mysql> insert into DemoTable values(40,20); ERROR 1062 (23000): Duplicate entry '20' for key 'Value2' mysql> insert into DemoTable values(60,70); Query OK, 1 row affected (1.37 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+--------+ | Value | Value2 | +-------+--------+ | 10 | 20 | | 60 | 70 | +-------+--------+ 2 rows in set (0.00 sec)
Advertisements