TechnicalEasy SQL & Databases

Explain the different types of SQL JOINs.

Asked for Backend Developer, Full-Stack Developer

Why they ask this: Joining tables is daily backend work and a staple of online tests in Nepal.

Answer

  • INNER JOIN: only rows that match in both tables.
  • LEFT JOIN: all rows from the left table, plus matches from the right. Missing matches come back as NULL.
  • RIGHT JOIN: the mirror of LEFT JOIN.
  • FULL OUTER JOIN: all rows from both tables. MySQL does not support it directly; combine a LEFT and a RIGHT JOIN with UNION.
  • CROSS JOIN: every combination of rows (a Cartesian product).
  • SELF JOIN: a table joined to itself, for example employees and their managers.
sql
-- Every company, with its job count (including companies with no jobs)
SELECT c.name, COUNT(j.id) AS jobs
FROM companies c
LEFT JOIN jobs j ON j.company_id = c.id
GROUP BY c.id, c.name;

Note that COUNT(j.id) counts only matched rows, while COUNT(*) would count 1 for a company with no jobs.

Can you explain this in your own words?

Back to question bank