Select distinct names from two columns in MySQL and display the result in a single column

MySQLMySQLi Database

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

mysql> create table DemoTable
(
   Name1 varchar(100),
   Name2 varchar(100)
);
Query OK, 0 rows affected (0.58 sec)

Insert some records in the table using insert command

mysql> insert into DemoTable values('Adam','Bob');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values('Adam','Bob');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('David','Chris');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+-------+
| Name1 | Name2 |
+-------+-------+
| Adam  | Bob   |
| Adam  | Bob   |
| David | Chris |
+-------+-------+
3 rows in set (0.00 sec)

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

mysql> select Name1 from DemoTable
UNION
select Name2 from DemoTable;

This will produce the following output −

+-------+
| Name1 |
+-------+
| Adam  |
| David |
| Bob   |
| Chris |
+-------+
4 rows in set (0.02 sec)
raja
Published on 25-Sep-2019 11:12:38
Advertisements