- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Select distinct names from two columns in MySQL and display the result in a single column
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)
Advertisements