Junior — Middle
Explain the concept of table joins in SQL and how it is used to retrieve related data.
sobes.tech AI
Answer from AI
Joining tables (JOIN) in SQL is used to retrieve related data from two or more tables based on a logical condition, usually related to keys.
Main types of joins:
- INNER JOIN — returns rows with matches in both tables.
- LEFT JOIN (LEFT OUTER JOIN) — returns all rows from the left table and matching rows from the right; if no match, NULLs are used.
- RIGHT JOIN (RIGHT OUTER JOIN) — the opposite, all from the right and matching from the left.
- FULL JOIN (FULL OUTER JOIN) — combines LEFT and RIGHT, returning all rows from both tables.
Example: there are tables orders and customers, where orders.customer_id references customers.id. To get a list of orders with customer information:
SELECT orders.id, customers.name, orders.amount
FROM orders
INNER JOIN customers ON orders.customer_id = customers.id;
Thus, JOIN allows linking data from different tables by keys and obtaining comprehensive information.