Junior — Middle
Explain the principle of LEFT JOIN in SQL and how it differs from other types of joins.
sobes.tech AI
Answer from AI
LEFT JOIN in SQL is used to combine two tables in such a way that all records from the left (first) table and the matching records from the right (second) table are included in the result. If there are no matches for a row in the left table, NULL values will be used for the columns of the right table.
Differences from other types of JOIN:
- INNER JOIN returns only the records that match in both tables.
- RIGHT JOIN returns all records from the right table and the matching ones from the left.
- FULL OUTER JOIN returns all records from both tables, filling in NULLs where there are no matches.
Example of LEFT JOIN:
SELECT A.id, A.name, B.order_date
FROM Customers A
LEFT JOIN Orders B ON A.id = B.customer_id;
This will display all customers, even if they have no orders (in this case, order_date will be NULL). This is useful when you want to keep all data from the main table and supplement it with information from the related table if available.