Joining Data in SQL
Maham Faisal Khan
Senior Content Developer, DataCamp

INNER JOIN looks for records in both tables which match on a given field INNER JOIN on the id field
INNER JOIN ON the id field
INNER JOIN ON the id field
World leaders up to 2024:

SELECT *
FROM presidents;
| country | continent | president |
|----------|---------------|-------------------------|
| Egypt | Africa | Abdel Fattah el-Sisi |
| Portugal | Europe | Marcelo Rebelo de Sousa |
| USA | North America | Joe Biden |
| Uruguay | South America | Luis Lacalle Pou |
| Pakistan | Asia | Asif Ali Zardari |
| Chile | South America | Gabriel Boric |
| India | Asia | Droupadi Murmu |
prime_ministers table
presidents table
prime_ministers table
--Inner join of presidents and prime_ministers, joining on countrySELECT prime_ministers.country, prime_ministers.continent, prime_minister, presidentFROM presidentsINNER JOIN prime_ministersON presidents.country = prime_ministers.country;
Note. The table.column_name format must be used when selecting columns that exist in both tables to avoid a SQL error.
| country | continent | prime_minister | president |
|----------------|-----------|------------------|-------------------------|
| Egypt | Africa | Mostafa Madbouly | Abdel Fattah el-Sisi |
| Portugal | Europe | Luís Montenegro | Marcelo Rebelo de Sousa |
| Pakistan | Asia | Shehbaz Sharif | Asif Ali Zardari |
| India | Asia | Narendra Modi | Ram Nath Kovind |
--Inner join of presidents and prime_ministers, joining on countrySELECT p2.country, p2.continent, prime_minister, presidentFROM presidents AS p1 INNER JOIN prime_ministers AS p2ON p1.country = p2.country;
| country | continent | prime_minister | president |
|----------------|-----------|------------------|-------------------------|
| Egypt | Africa | Mostafa Madbouly | Abdel Fattah el-Sisi |
| Portugal | Europe | Luís Montenegro | Marcelo Rebelo de Sousa |
| Pakistan | Asia | Shehbaz Sharif | Asif Ali Zardari |
| India | Asia | Narendra Modi | Ram Nath Kovind |
Aliases can be used in the table.column_name syntax in SELECT and ON clauses.
--Inner join of presidents and prime_ministers, joining on country
SELECT p2.country, p2.continent, prime_minister, president
FROM presidents AS p1
INNER JOIN prime_ministers AS p2
USING(country);
| country | continent | prime_minister | president |
|----------------|-----------|------------------|-------------------------|
| Egypt | Africa | Mostafa Madbouly | Abdel Fattah el-Sisi |
| Portugal | Europe | Luís Montenegro | Marcelo Rebelo de Sousa |
| Pakistan | Asia | Shehbaz Sharif | Asif Ali Zardari |
| India | Asia | Narendra Modi | Ram Nath Kovind |
Joining Data in SQL