Junior — Middle
Can you list the types of joins in SQL and explain their differences?
sobes.tech AI
Answer from AI
In SQL, there are several main types of joins that allow you to combine rows from two tables based on a specific condition:
- INNER JOIN — returns only the rows where there are matches in both tables.
- LEFT JOIN (LEFT OUTER JOIN) — returns all rows from the left table and the matching rows from the right; if there are no matches, the columns from the right table will be NULL.
- RIGHT JOIN (RIGHT OUTER JOIN) — similar to LEFT JOIN, but returns all rows from the right table and the matching rows from the left.
- FULL JOIN (FULL OUTER JOIN) — returns all rows from both tables; if there are no matches, the corresponding columns will be NULL.
- CROSS JOIN — Cartesian product; each row from the first table is combined with each row from the second.
Example:
SELECT * FROM A
INNER JOIN B ON A.id = B.a_id;
Will return only those records where A.id matches B.a_id.
Differences in which rows are preserved when there are no matches:
- INNER JOIN — only matching rows.
- LEFT JOIN — all from the left + matching from the right.
- RIGHT JOIN — all from the right + matching from the left.
- FULL JOIN — all from both.
This allows flexible data selection depending on the task.