Sobes.tech
Middle

What is a JOIN? What types of JOINs exist and what are their differences?

sobes.tech AI

Answer from AI

JOIN is an operation in SQL that allows you to combine rows from two or more tables based on a related condition.

Main types of JOIN:

  • INNER JOIN — returns only those records that have matches in both tables.
  • LEFT JOIN (LEFT OUTER JOIN) — returns all records from the left table and matching records from the right; if there are no matches, NULLs are shown on the right.
  • RIGHT JOIN (RIGHT OUTER JOIN) — the opposite, returns all from the right table and matching from the left.
  • FULL JOIN (FULL OUTER JOIN) — returns all records from both tables, filling in NULLs where there are no matches.
  • CROSS JOIN — Cartesian product, returns all possible combinations of rows from both tables.

Differences in which rows are included in the result when there are no matches:

  • INNER JOIN excludes them.
  • LEFT/RIGHT JOIN includes all from one table and matching from the other.
  • FULL JOIN includes all from both.

Example of INNER JOIN:

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

This query will return users who have orders.