Joins

Combine tables with INNER JOIN and LEFT JOIN.

A join links rows from two tables on a shared column. INNER JOIN keeps only rows that match on both sides.

SQL
SELECT s.name, e.course
FROM students s
JOIN enrolments e ON e.student_id = s.id
ORDER BY s.name, e.course;
Output
Asha | Java
Asha | Python
Chitra | SQL
Esther | Python

LEFT JOIN

LEFT JOIN keeps every row from the left table, with NULL where nothing matched. Use it to find what is missing.

SQL
SELECT s.name
FROM students s
LEFT JOIN enrolments e ON e.student_id = s.id
WHERE e.student_id IS NULL
ORDER BY s.name;
Output
Bala
Dinesh

Test for missing values with IS NULL. Writing = NULL never matches.

โ† Counting and groupingSubqueries โ†’