JOINS and UNION Examples - SQL Query
What is the difference between JOINS and UNION.
Joins: A join is used to display columns with the same or different names from different tables. All columns are shown individually in the output.
Union: The UNION operator is used to combine data from two tables with same data type. When UNION is performed, the data from both tables will be collected in a single column which has a same data type.
Example: UNION Operator.
Consider the following tables.
Table1: Supplier
| Supplier_ID | Supplier_Name |
|---|
| 100 | Samsung |
| 200 | Sony |
| 300 | Micromax |
Table2: Orders
| Order_ID | Supplier_ID |
|---|
| 1 | 200 |
| 2 | 400 |
| 3 | 500 |
| 4 | 600 |
Q. Write a query to perform UINON on column 'Customer_ID' from Table1 and Table2.
Answer:
SELECT Supplier_ID FROM Supplier
UNION
SELECT Supplier_ID FROM Orders
ORDER BY Supplier_ID
This query will show the union of Supplier_ID column.
Output:
| Supplier_ID |
|---|
| 100 |
| 200 |
| 300 |
| 400 |
| 500 |
| 600 |
Note: The union operator is used to avoid duplication of records. So the value 200 which is appear in the column Supplier_ID which is present in the both tables is displayed only once to avoid duplication.