Explain the differences between inner join, outer join, left join, and right join in SQL.
sobes.tech AI
Answer from AI
In SQL, there are different types of joins that determine how rows from two tables are combined:
-
Inner Join — returns only those rows that have matching values in both tables based on the join condition.
-
Outer Join — returns all rows from one table and the matching rows from the other. If there is no match, the fields from the other table will be filled with NULL.
Outer joins come in two types:
-
Left Outer Join — returns all rows from the left table and the matching rows from the right table. If there is no match, the right table's fields will be NULL.
-
Right Outer Join — returns all rows from the right table and the matching rows from the left table.
Example:
SELECT * FROM A
INNER JOIN B ON A.id = B.a_id; -- only matching rows
SELECT * FROM A
LEFT JOIN B ON A.id = B.a_id; -- all from A + matches from B
SELECT * FROM A
RIGHT JOIN B ON A.id = B.a_id; -- all from B + matches from A
Thus, the choice of join type depends on what data you need to retrieve: only matching rows or all from one table with possible NULLs from the other.