Insert non-duplicates value in a MySQL table

MySQLMySQLi Database

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)
raja
Published on 03-Sep-2019 12:40:19
Advertisements