How to ensure that MySQL rows are unique?

MySQLMySQLi Database

To ensure that MySQL rows are unique, you need to use UNIQUE constraint. Let us first create a table −

mysql> create table DemoTable1580
   -> (
   -> id int,
   -> Name varchar(20),
   -> Age int
   -> );
Query OK, 0 rows affected (0.73 sec)

Here is the query to create unique constraints to ensure MySQL rows are unique −

mysql> alter table DemoTable1580 add unique index(id,Name,Age);
Query OK, 0 rows affected (0.45 sec)
Records: 0  Duplicates: 0  Warnings: 0

Insert some records in the table using insert command −

mysql> insert into DemoTable1580 values(101,'Chris',21);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable1580 values(102,'Chris',21);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1580 values(102,'David',21);
Query OK, 1 row affected (0.49 sec)
mysql> insert into DemoTable1580 values(101,'Chris',21);
ERROR 1062 (23000): Duplicate entry '101-Chris-21' for key 'id'

Display all records from the table using select statement −

mysql> select * from DemoTable1580;

This will produce the following output −

+------+-------+------+
| id   | Name  | Age  |
+------+-------+------+
|  101 | Chris |   21 |
|  102 | Chris |   21 |
|  102 | David |   21 |
+------+-------+------+
3 rows in set (0.00 sec)
raja
Published on 16-Dec-2019 06:16:48
Advertisements