SQL JOIN Notes
SQL JOIN is used to combine rows from two or more tables based on a related column.
Types of Joins:
1. INNER JOIN - Only matching rows from both tables
2. LEFT JOIN - All rows from left table + matched rows from right
3. RIGHT JOIN - All rows from right table + matched rows from left
4. FULL JOIN - All rows from both tables (not in MySQL directly)
5. CROSS JOIN - All combinations (Cartesian product)
Basic Syntax:
SELECT table1.column1, table2.column2
FROM table1
JOIN table2 ON table1.common_column = table2.common_column;
Example:
Tables:
students(id, name)
marks(student_id, score)
INNER JOIN:
SELECT students.name, marks.score
FROM students
INNER JOIN marks ON students.id = marks.student_id;
LEFT JOIN:
SELECT students.name, marks.score
FROM students
LEFT JOIN marks ON students.id = marks.student_id;
Alias Tip:
SELECT s.name, m.score
FROM students s
JOIN marks m ON s.id = m.student_id;