Computer >> Computer tutorials >  >> Programming >> MySQL

Insert multiple rows from another table but the inserted records should be distinct


For this, you can use DISTINCT along with the INSERT INTO SELECT statement. Let us first create a table −

mysql> create table DemoTable1
(
   Value int
);
Query OK, 0 rows affected (1.03 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(50);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1 values(10);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1 values(10);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1 values(60);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1 values(50);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1 values(70);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1 values(50);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+-------+
| Value |
+-------+
|    50 |
|    10 |
|    10 |
|    60 |
|    50 |
|    70 |
|    50 |
+-------+
7 rows in set (0.00 sec)

Following is the query to create the second table.

mysql> create table DemoTable2
(
   Marks int
);
Query OK, 0 rows affected (1.20 sec)

Following is the query to insert multiple rows from another table. The inserted records should be distinct −

mysql> insert into DemoTable2(Marks) select distinct Value from DemoTable1;
Query OK, 4 rows affected (0.18 sec)
Records: 4 Duplicates: 0 Warnings: 0

Display all records from the table using select statement −

mysql> select *from DemoTable2;

This will produce the following output −

+-------+
| Marks |
+-------+
|    50 |
|    10 |
|    60 |
|    70 |
+-------+
4 rows in set (0.00 sec)