Joining Data in SQL
Maham Faisal Khan
Senior Content Developer, DataCamp
UNION
takes two tables as input, and returns all records from both tablesUNION ALL
takes two tables and returns all records from both tables, including duplicatesSELECT *
FROM left_table
UNION
SELECT *
FROM right_table;
SELECT *
FROM left_table
UNION ALL
SELECT *
FROM right_table;
SELECT *
FROM monarchs;
| country | continent | monarch |
|----------------|-------------|-------------------------|
| Brunei | Asia | Hassanal Bolkiah |
| Oman | Asia | Haitham bin Tarik |
| Norway | Europe | Harald V |
| United Kingdom | Europe | Charles III |
SELECT monarch AS leader, country
FROM monarchs
UNION
SELECT prime_minister, country
FROM prime_ministers
ORDER BY country, leader
LIMIT 10;
|-------------------------|----------------|
| leader | country |
|-------------------------|----------------|
| Anthony Albanese | Australia |
| Hassanal Bolkiah | Brunei |
| Mostafa Madbouly | Egypt |
| Narendra Modi | India |
| Christopher Luxon | New Zealand |
| Harald V | Norway |
| Jonas Gahr Støre | Norway |
| Haitham bin Tarik | Oman |
| Shehbaz Sharif | Pakistan |
| Luís Montenegro | Portugal |
|-------------------------|----------------|
SELECT monarch AS leader, country
FROM monarchs
UNION ALL
SELECT prime_minister, country
FROM prime_ministers
ORDER BY leader, country
LIMIT 10;
| leader | country |
|-------------------------|----------------|
| Anthony Albanese | Australia |
| Hassanal Bolkiah | Brunei |
| Hassanal Bolkiah | Brunei |
| Mostafa Madbouly | Egypt |
| Narendra Modi | India |
| Christopher Luxon | New Zealand |
| Harald V | Norway |
| Jonas Gahr Støre | Norway |
| Haitham bin Tarik | Oman |
| Haitham bin Tarik | Oman |
Joining Data in SQL