Sobes.tech
Junior — Middle

Explain the differences between the various types of table joins in SQL.

sobes.tech AI

Answer from AI

In SQL, there are several main types of joins that allow you to combine data from two or more tables:

  • INNER JOIN — returns only the records that have matches in both tables.
  • LEFT JOIN (or LEFT OUTER JOIN) — returns all records from the left table and the matching records from the right; if there are no matches, the right side will contain NULL.
  • RIGHT JOIN (or RIGHT OUTER JOIN) — returns all records from the right table and the matching ones from the left.
  • FULL JOIN (or FULL OUTER JOIN) — returns all records from both tables, filling NULL where there are no matches.

Example:

SELECT users.name, orders.id
FROM users
LEFT JOIN orders ON users.id = orders.user_id;

This query will return all users and their orders if they exist; if there are no orders, the fields from orders will be NULL.