Select distinct values from two columns in MySQL?

MySQLMySQLi Database

To select distinct values from two columns, use UNION. Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(1);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1 values(2);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable1 values(3);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1 values(4);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+--------+
| Value1 |
+--------+
|      1 |
|      2 |
|      3 |
|      4 |
+--------+
4 rows in set (0.00 sec)

Following is the query to create the second table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values(3);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable2 values(4);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable2 values(5);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable2 values(6);
Query OK, 1 row affected (0.08 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2;

This will produce the following output −

+--------+
| Value2 |
+--------+
|      3 |
|      4 |
|      5 |
|      6 |
+--------+
4 rows in set (0.00 sec)

Following is the query to select distinct values from two columns −

mysql> select Value1 from DemoTable1
UNION
select Value2 from DemoTable2;

This will produce the following output −

+--------+
| Value1 |
+--------+
|      1 |
|      2 |
|      3 |
|      4 |
|      5 |
|      6 |
+--------+
6 rows in set (0.00 sec)
raja
Published on 26-Sep-2019 11:32:52
Advertisements