SQL provides several types of joins to combine data from multiple tables, including:
INNER JOIN
Syntax:
1 2 3 4 5 |
SELECT [column1, column2, ...] FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name; |
Example:
1 2 3 4 5 |
SELECT cars.model, cars.color, owners.name FROM cars INNER JOIN owners ON cars.id = owners.car_id; |
LEFT JOIN
(or LEFT OUTER JOIN) Syntax:
1 2 3 4 5 |
SELECT [column1, column2, ...] FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name; |
Example:
1 2 3 4 5 |
SELECT cars.model, cars.color, owners.name FROM cars LEFT JOIN owners ON cars.id = owners.car_id; |
RIGHT JOIN
(or RIGHT OUTER JOIN) Syntax:
1 2 3 4 5 |
SELECT [column1, column2, ...] FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name; |
Example:
1 2 3 4 5 |
SELECT cars.model, cars.color, owners.name FROM cars RIGHT JOIN owners ON cars.id = owners.car_id; |
FULL OUTER JOIN
Syntax:
1 2 3 4 5 |
SELECT [column1, column2, ...] FROM table1 FULL OUTER JOIN table2 ON table1.column_name = table2.column_name; |
Example:
1 2 3 4 5 |
SELECT cars.model, cars.color, owners.name FROM cars FULL OUTER JOIN owners ON cars.id = owners.car_id; |
Note: In the examples above, the cars
and owners
tables are assumed to have columns named id
, model
, color
, and name
respectively. The actual syntax may vary depending on the SQL database you are using.