Sobes.tech
Junior

What is the difference between JOIN and UNION?

sobes.tech AI

Answer from AI

JOIN combines rows from two or more tables based on a related column between them. UNION combines the result sets of two or more SELECT queries into a single result set.

Key differences:

Characteristic JOIN UNION
Purpose Combining columns from different tables Combining rows from different result sets
Requirements Presence of a common column for joining Same number of columns and compatible data types in SELECT queries
Types INNER, LEFT, RIGHT, FULL UNION (removes duplicates), UNION ALL (keeps duplicates)

Example of JOIN (SQL):

SELECT
    Customers.CustomerName,
    Orders.OrderID
FROM
    Customers
INNER JOIN
    Orders ON Customers.CustomerID = Orders.CustomerID;

Example of UNION (SQL):

SELECT City FROM Customers
UNION
SELECT City FROM Suppliers;