
- 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
How to 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)
- Related Articles
- How to prevent duplicate INSERT in MySQL?
- How to prevent MySQL double insert (duplicate entry)?
- How to avoid inserting duplicate rows in MySQL?
- How to insert multiple rows with single MySQL query?
- How to prevent duplicate JavaScript Variables Declaration?
- Finding Duplicate Rows in MySQL (Composite Key)?
- Implement INSERT … ON DUPLICATE KEY UPDATE in MySQL
- Implementing INSERT… ON DUPLICATE KEY UPDATE in MySQL
- Correct MySQL INSERT ... ON DUPLICATE KEY syntax?
- How can we use MySQL REPLACE statement to prevent of insertion of duplicate data?
- How to Automatically Insert Rows in Excel?
- Insert multiple rows in a single MySQL query
- How to drop duplicate rows in pandas series?
- How to find and filter Duplicate rows in Pandas ?
- MySQL rows concatenation to fetch maximum corresponding value from duplicate IDs?

Advertisements