Junior — Middle
Can you explain the differences between table join types in SQL?
sobes.tech AI
Answer from AI
In SQL, there are different types of joins that allow combining data from two or more tables:
- INNER JOIN — returns only the rows where there are matches in both tables.
- LEFT JOIN (or LEFT OUTER JOIN) — returns all rows from the left table and matching rows from the right; if there are no matches, NULLs will appear in the right table's columns.
- RIGHT JOIN (or RIGHT OUTER JOIN) — the opposite, returns all rows from the right table and matching rows from the left.
- FULL JOIN (or FULL OUTER JOIN) — returns all rows from both tables, matching where possible, filling NULLs where there is no match.
- CROSS JOIN — Cartesian product of two tables, each row of the first table is combined with each row of the second.
Example:
SELECT * FROM A
INNER JOIN B ON A.id = B.a_id;
Returns only the rows where A.id matches B.a_id.
Understanding the differences is important for constructing correct queries and obtaining the desired data.