Sobes.tech
Junior — Middle

Explain the difference between inner join and left join in SQL and when each is used.

sobes.tech AI

Answer from AI

Inner join returns only those rows that have matches in both tables based on the join condition. If there are no matches, the row is not included in the result.

Left join returns all rows from the left table and the matching rows from the right table. If there is no match for a row in the left table, the result will include the values from the left table and NULL for the right table.

INNER JOIN is used when only matching data from both tables is needed, for example, to get a list of orders with customer information only if the customer exists.

LEFT JOIN is used when it is important to keep all data from the left table, even if there are no matching records in the right table, for example, to get all customers and their orders, including customers without orders.

Example:

SELECT customers.name, orders.id
FROM customers
LEFT JOIN orders ON customers.id = orders.customer_id;