Database.Beginner.What are the different types of JOINs in SQL?

Main Types of JOINs

JOIN TypeWhat It Does
INNER JOINReturns rows where there’s a match in both tables.
LEFT JOINReturns all rows from the left table, plus matches from the right (NULL if no match).
RIGHT JOINReturns all rows from the right table, plus matches from the left (NULL if no match).
FULL OUTER JOINReturns all rows from both tables — matches where possible, NULLs where no match.
CROSS JOINReturns every combination of rows — Cartesian product (no ON condition).
SELF JOINJoin a table to itself — used when you need to compare rows within the same table.

1. INNER JOIN

  • Only rows with matching keys in both tables are returned.
SELECT * FROM A
INNER JOIN B ON A.id = B.a_id;
A.idA.nameB.idB.a_idB.title
1Alice101Manager

➡️ Only rows where A.id = B.a_id.

2. LEFT JOIN (LEFT OUTER JOIN)

  • All rows from the left table, matched rows from right table, NULLs where no match.
SELECT * FROM A
LEFT JOIN B ON A.id = B.a_id;
A.idA.nameB.idB.a_idB.title
1Alice101Manager
2BobNULLNULLNULL

➡️ Bob is shown even though he has no match.

3. RIGHT JOIN (RIGHT OUTER JOIN)

  • All rows from the right table, matched rows from left table, NULLs where no match.
SELECT * FROM A
RIGHT JOIN B ON A.id = B.a_id;
A.idA.nameB.idB.a_idB.title
1Alice101Manager
NULLNULL115Engineer

➡️ Even if B.a_id = 5 has no match in A, it shows up with NULLs from A.

4. FULL OUTER JOIN

  • All rows from both tables — match if possible, NULLs if not.
A.id	A.name	B.id	B.a_id	B.title
1	Alice	10	1	Manager
2	Bob	NULL	NULL	NULL
NULL	NULL	11	5	Engineer

➡️ Combines the behavior of LEFT and RIGHT JOINs.

5. CROSS JOIN

  • Every row of A is paired with every row of B (no condition).
SELECT * FROM A
CROSS JOIN B;

If A has 3 rows and B has 2 rows ➔ 3 × 2 = 6 rows result.

A.idA.nameB.idB.title
1Alice10Manager
1Alice11Engineer
2Bob10Manager
2Bob11Engineer

6. SELF JOIN

  • Join a table to itself — useful for hierarchies, like employees and managers.
SELECT A.name AS employee, B.name AS manager
FROM Employees A
JOIN Employees B ON A.manager_id = B.id;
employeemanager
BobAlice

➡️ Bob’s manager is Alice.


Summary Table

JOIN TypeKey Idea
INNER JOINMatches in both tables.
LEFT JOINAll left rows, matched right rows.
RIGHT JOINAll right rows, matched left rows.
FULL OUTER JOINAll rows from both sides.
CROSS JOINAll combinations — Cartesian product.
SELF JOINTable joined to itself.

🎨 Quick Sketch in Text

JOIN TypeDiagramDescription
INNER JOIN(🟢 ∩ 🔵)Only common (intersection).
LEFT JOIN🟢 + (🟢 ∩ 🔵)All A, and matches from B (else NULL).
RIGHT JOIN🔵 + (🟢 ∩ 🔵)All B, and matches from A (else NULL).
FULL OUTER JOIN(🟢 ∪ 🔵)All from A and B, NULL if no match.
CROSS JOIN🟢 × 🔵Every A row with every B row (Cartesian).
SELF JOINA ↔ AA table joined to itself.
This entry was posted in Без рубрики. Bookmark the permalink.