Learn INNER, LEFT, RIGHT, FULL, CROSS Joins & Self-Joins
Master SQL joins and table relationships in this beginner-friendly guide. Learn INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, CROSS JOIN, self-joins, and foreign key relationships. Practice joining Employees and Departments, listing employees without departments, and fetching students with enrolled courses.
1. Introduction
Joins allow you to combine data from multiple tables based on a related column, usually a foreign key.
They are essential for relational databases to extract meaningful information from multiple tables.
2. Types of Joins
2.1 INNER JOIN
- Returns only matching rows from both tables.
Syntax:
Example:
2.2 LEFT JOIN (LEFT OUTER JOIN)
- Returns all rows from the left table, and matching rows from the right table.
- If no match, right table columns are NULL.
Example:
2.3 RIGHT JOIN (RIGHT OUTER JOIN)
- Returns all rows from the right table, and matching rows from the left table.
Example:
2.4 FULL OUTER JOIN
- Returns all rows from both tables, matching where possible, and NULL where there is no match.
Example:
2.5 CROSS JOIN
- Returns all possible combinations of rows from both tables.
Example:
2.6 Self-Join
- Joins a table to itself to compare rows within the same table.
Example:
3. Foreign Key Relationships
- A foreign key links a column in one table to a primary key in another.
- Ensures referential integrity between tables.
Example:
4. Practical Exercises
- Join Employees and Departments to display employee names with department names.
- List all employees without departments using LEFT JOIN.
- Fetch students with their enrolled courses using INNER JOIN.
- Use CROSS JOIN to list all possible employee-department combinations.
- Use a self-join to find employees in the same department.
5. Tips for Beginners
- Always identify common columns to join tables.
- Choose the join type based on whether you want all rows or only matching rows.
- Use aliases (
e1,e2) for clarity, especially with self-joins. - Foreign keys enforce data consistency and simplify joins.
Next Step: After mastering joins and relationships, the next module is Subqueries, where you’ll learn to write queries within queries, including correlated and non-correlated subqueries.