7. Joins
Description
A JOIN combines data from two or more tables using related columns (usually foreign keys). When related data is spread across several tables, joins let you retrieve it as one result.
SELECT column_name(s)
FROM table1
JOIN table2 ON table1.column_name = table2.column_name;
SELECT: columns to retrieve;FROM: the primary table;JOIN: the table to combine;ON: the matching condition (e.g.,passenger_idin both tables).
Part I: INNER and OUTER Joins
INNER JOIN
Returns only the rows that have matching values in both tables.
SELECT p.first_name, b.flight_id
FROM passengers p
INNER JOIN booking b ON p.passenger_id = b.passenger_id;
Joining several tables:
SELECT column1, column2
FROM table1
INNER JOIN table2 ON condition_1
INNER JOIN table3 ON condition_2;
OUTER JOINS
Return rows even when there is no counterpart in the other table.
| Join | Returns |
|---|---|
LEFT JOIN (LEFT OUTER) | All rows of the left table, plus matching rows from the right (NULL where no match) |
RIGHT JOIN (RIGHT OUTER) | All rows of the right table, plus matching rows from the left (NULL where no match) |
FULL JOIN (FULL OUTER) | All rows from both tables, with NULL filled in where there is no match on either side |
SELECT * FROM table1 LEFT JOIN table2 ON table1.id = table2.id;
SELECT * FROM table1 RIGHT JOIN table2 ON table1.id = table2.id;
SELECT * FROM table1 FULL JOIN table2 ON table1.id = table2.id;
Part II: NATURAL, SELF and CROSS Joins
NATURAL JOIN
Creates an implicit join on all columns with the same name in both tables.
SELECT select_list FROM T1 NATURAL [INNER | LEFT | RIGHT] JOIN T2;
Convenient when tables share several common columns, but can give unexpected results if column names coincide by accident.
SELF JOIN
A regular join of a table to itself, using aliases. Used for hierarchical data or for comparing rows within one table.
SELECT e.name AS employee, m.name AS manager
FROM employee e
INNER JOIN employee m ON e.manager_id = m.employee_id;
CROSS JOIN
Produces the Cartesian product of the rows of two or more tables (every row of T1 combined with every row of T2).
SELECT select_list FROM T1 CROSS JOIN T2;
Comparison
| Join | Use when |
|---|---|
| INNER | You only want rows matching in both tables |
| LEFT / RIGHT | You want all rows from one side regardless of a match |
| FULL OUTER | You want everything from both sides |
| NATURAL | Tables share identically named join columns (use with care) |
| SELF | A table references itself (hierarchies, comparing rows) |
| CROSS | You need every combination of rows |
Conclusion
Joins are the main tool for reassembling normalized data. Choosing the right join type determines which unmatched rows are kept or dropped.
All rights remain with the original author (Algo-holics). Publishing here does not grant a license to copy or reuse this text. Copyright & license. If you noticed a mistake or copyright issues, please contact: lebroskiofficial@proton.me