Good database design splits data into several tables (students, departments, courses...) to avoid repetition. To answer real questions - which department is Aarav in? who scored highest in Java Programming? - you join the tables back together using their keys.
INNER JOIN#
INNER JOIN (or just JOIN) pairs rows from two tables where the join condition is true:
Table aliases make joins shorter and are essential when both tables have a column with the same name (name here):
JOIN दो tables को उनकी common key (जैसे dept_id) से जोड़ता है। students में सिर्फ़ dept_id = 1 लिखा है; department का नाम departments table में है। ON s.dept_id = d.dept_id बताता है कि किस row को किससे जोड़ना है। INNER JOIN में सिर्फ़ वही rows आती हैं जिनका जोड़ीदार दोनों tables में मिले।
Count the result: 29 rows, not 30. Om Malviya has dept_id = NULL, so he has no match and an inner join drops him.
LEFT JOIN - keep everything on the left#
LEFT JOIN returns all rows of the left table; where there is no match, the right side's columns are NULL:
Finding rows with no match#
A LEFT JOIN followed by WHERE right.key IS NULL finds "orphans" - one of the most useful patterns in SQL:
Joins with GROUP BY#
COUNT(s.student_id) (not COUNT(*)) gives 0 for Data Science, because the NULL produced by the left join is not counted.
Joining three or more tables#
enrollments connects students and courses (a many-to-many relationship). Chain joins to build a marksheet:
(The bracketed query inside is a subquery - next lesson.)
Self join#
A table can be joined with itself. faculty.reports_to points to another row of faculty:
RIGHT JOIN, FULL OUTER JOIN and CROSS JOIN#
RIGHT JOIN- like LEFT JOIN with the tables swapped (keep all rows of the right table). Most people simply swap the tables and use LEFT JOIN.FULL OUTER JOIN- all rows from both sides, matched where possible. Supported in PostgreSQL, SQL Server and SQLite 3.39+; MySQL emulates it withLEFT JOIN ... UNION ... RIGHT JOIN.CROSS JOIN- every combination of rows (a Cartesian product). Useful for generating combinations, dangerous by accident.
Forgetting the ON condition (or writing FROM a, b without a WHERE link) silently creates a cross join: 30 students × 6 departments = 180 rows of nonsense. If a join returns far more rows than expected, check the join conditions first.
Join types at a glance#
| Join | Returns |
|---|---|
INNER JOIN |
only matching pairs |
LEFT JOIN |
all left rows + matches (NULL if none) |
RIGHT JOIN |
all right rows + matches |
FULL OUTER JOIN |
all rows from both sides |
CROSS JOIN |
every combination |
| self join | a table joined to itself via aliases |
Summary#
- Join tables on their keys:
FROM a JOIN b ON a.key = b.key; use aliases. - INNER JOIN keeps matches only; LEFT JOIN keeps all rows of the left table.
LEFT JOIN ... WHERE right.key IS NULLfinds unmatched rows.- Chain joins for many-to-many relationships; self joins handle hierarchies.