SQL Joins
β± Estimated reading time: 3 min
SQL JOIN is a powerful feature used to combine rows from two or more tables based on a related column between them. Joins help retrieve meaningful data from multiple tables by establishing relationships using primary key β foreign key connections.
Joins are essential in relational databases because data is stored in separate normalized tables, and queries often require combining these tables to produce meaningful results.
Types of SQL Joins
SQL supports several types of joins:
-
INNER JOIN
-
LEFT OUTER JOIN
-
RIGHT OUTER JOIN
-
FULL OUTER JOIN
-
CROSS JOIN
-
SELF JOIN
Letβs understand each in detail with examples.
1οΈβ£ INNER JOIN
Returns only the matching rows from both tables.
Syntax
Example
Student Table
| Sid | Name |
|---|---|
| 1 | Rahul |
| 2 | Neha |
| 3 | Amit |
Course Table
| Sid | Course |
|---|---|
| 1 | BCA |
| 3 | MCA |
Query
Output
| Name | Course |
|---|---|
| Rahul | BCA |
| Amit | MCA |
Only matching rows are returned.
2οΈβ£ LEFT OUTER JOIN (LEFT JOIN)
Returns all rows from the left table, and matched rows from the right table.
Non-matching rows from the right table become NULL.
Syntax
Output Example
From the previous tables:
| Name | Course |
|---|---|
| Rahul | BCA |
| Neha | NULL |
| Amit | MCA |
Neha has no matching course, so NULL appears.
3οΈβ£ RIGHT OUTER JOIN (RIGHT JOIN)
Returns all rows from the right table, and matched rows from the left table.
Syntax
Output Example
(Using Student and Course tables)
| Name | Course |
|---|---|
| Rahul | BCA |
| Amit | MCA |
If any course exists without a student, it would appear with NULL values from Student.
4οΈβ£ FULL OUTER JOIN
Returns all rows from both tables, with NULL where no match exists.
(Some DBMS like MySQL donβt support FULL OUTER JOIN directly.)
Syntax
Output Example
| Name | Course |
|---|---|
| Rahul | BCA |
| Neha | NULL |
| Amit | MCA |
| NULL | MBA |
(This would happen if a course existed without a student.)
5οΈβ£ CROSS JOIN
Produces the Cartesian product of two tables.
Rows = rows in table1 Γ rows in table2.
Syntax
Example
If Student has 3 rows and Course has 2 rows β Output = 6 rows.
6οΈβ£ SELF JOIN
Self join means joining a table with itself.
Use Case
Finding employees and their managers in the same table.
Syntax
Differences Between Joins
| Join Type | Β Returns |
|---|---|
| INNER JOIN | Only matching rows |
| LEFT JOIN | All left + matched right |
| RIGHT JOIN | All right + matched left |
| FULL JOIN | All rows from both tables |
| CROSS JOIN | Cartesian product |
| SELF JOIN | Table joined with itself |
Conclusion
SQL Joins enable combining data from multiple related tables, making relational databases powerful and efficient. INNER JOIN is most commonly used, while LEFT JOIN is useful when unmatched rows must be included. FULL JOIN, CROSS JOIN, and SELF JOIN serve special use cases. Understanding joins is essential for writing complex SQL queries.
Register Now
Share this Post
β Back to Tutorials