
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Prevent Duplicate Rows in MySQL Insert
For this, you need to use UNIQUE KEY for the column. Let us first create a table −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(30), UNIQUE KEY(FirstName) ); Query OK, 0 rows affected (1.76 sec)
Insert some records in the table using insert command. Now, we are also inserting duplicate records like “David”, but it won’t get inserted twice, since we have set the column as UNIQUE KEY −
mysql> insert ignore into DemoTable(FirstName) values('Chris'); Query OK, 1 row affected (0.42 sec) mysql> insert ignore into DemoTable(FirstName) values('David'); Query OK, 1 row affected (0.12 sec) mysql> insert ignore into DemoTable(FirstName) values('Chris'); Query OK, 0 rows affected, 1 warning (0.17 sec) mysql> insert ignore into DemoTable(FirstName) values('Sam'); Query OK, 1 row affected (0.11 sec) mysql> insert ignore into DemoTable(FirstName) values('David'); Query OK, 0 rows affected, 1 warning (0.07 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+-----------+ | Id | FirstName | +----+-----------+ | 1 | Chris | | 2 | David | | 4 | Sam | +----+-----------+ 3 rows in set (0.00 sec)
Advertisements