How to select and display a list of values in one column that are available in two different MySQL columns?

MySQLMySQLi Database

For this, use UNION ALL. Let us first create a table −

mysql> create table DemoTable1813
     (
     Name1 varchar(20),
     Name2 varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1813 values('John','Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1813 values('Adam','Robert');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1813 values('Mike','Sam');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1813;

This will produce the following output −

+-------+--------+
| Name1 | Name2  |
+-------+--------+
| John  |  Chris |
| Adam  |  Robert|
| Mike  |    Sam |
+-------+--------+
3 rows in set (0.00 sec)

Here is the query to select a list of values in one column that are available in two different columns

mysql> select Name1 as Name from DemoTable1813
     union all
     select Name2 as Name from DemoTable1813;

This will produce the following output −

+--------+
| Name   |
+--------+
| John   |
| Adam   |
| Mike   |
| Chris  |
| Robert |
| Sam    |
+--------+
6 rows in set (0.00 sec)
raja
Published on 24-Dec-2019 10:45:52
Advertisements