
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Values from Two Columns in MySQL
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)
Advertisements