Sobes.tech
Junior — Middle

Explain the differences between LEFT JOIN and RIGHT JOIN when joining tables in SQL.

sobes.tech AI

Answer from AI

LEFT JOIN and RIGHT JOIN are types of table joins in SQL that determine which rows are preserved during the join.

  • LEFT JOIN returns all rows from the left table and the matching rows from the right table. If there are no matches in the right table, the right table fields will be filled with NULL.

  • RIGHT JOIN returns all rows from the right table and the matching rows from the left table. If there are no matches in the left table, the left table fields will be NULL.

Example:

SELECT * FROM A LEFT JOIN B ON A.id = B.a_id;
-- All records from A, with data from B if there are matches

SELECT * FROM A RIGHT JOIN B ON A.id = B.a_id;
-- All records from B, with data from A if there are matches

Thus, LEFT JOIN focuses on preserving all data from the left table, RIGHT JOIN — from the right.