- Trending Categories
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
Insert non-duplicates value in a MySQL table
To allow inserting only non-duplicate values, use the UNIQUE constraint. Let us first create a table −
mysql> create table DemoTable832( FirstName varchar(100), LastName varchar(100), UNIQUE(FirstName,LastName) ); Query OK, 0 rows affected (0.87 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable832 values('John','Smith'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable832 values('Adam','Smith'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable832 values('John','Doe'); Query OK, 1 row affected (0.33 sec) mysql> insert into DemoTable832 values('John','Smith'); ERROR 1062 (23000): Duplicate entry 'John-Smith' for key 'FirstName'
Above, we tried inserting a duplicate entry in the table, but an error can be seen.
Display all records from the table using select statement −
mysql> select *from DemoTable832;
This will produce the following output −
+-----------+----------+ | FirstName | LastName | +-----------+----------+ | Adam | Smith | | John | Doe | | John | Smith | +-----------+----------+ 3 rows in set (0.00 sec)
Advertisements