Understanding of SQL JOIN with Examples
SQL JOIN :-
FROM table1INNER JOIN table2ON table1.matching_column = table2.matching_column
Consider the below two table as follow,
SELECT Student.NAME,StudentCourse.COURSE_IDFROM StudentLEFT JOIN StudentCourseON StudentCourse.ROLL_NO = Student.ROLL_NO;
3) Right Join (Right Outer Join) :
This join returns all the rows of the table on the right side of the join and matching rows for the table on the left side of the join. For the rows for which there is no matching row on the left side, the result-set will contain null.
RIGHT JOIN is also known as RIGHT OUTER JOIN.
Example Queries(Right JOIN)
4) Full Outer Join(Full Join)SELECT Student.NAME,StudentCourse.COURSE_IDFROM StudentRIGHT JOIN StudentCourseON StudentCourse.ROLL_NO = Student.ROLL_NO;
FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT JOIN. The result-set will contain all the rows from both tables.
For the rows for which there is no matching, the result-set will contain NULL values.
Example Queries(Full JOIN)
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
5) Self Join :
- A self join allows you to join a table to itself.
- It helps query hierarchical data or compare rows within the same table
SELECT
e.first_name + ' ' + e.last_name employee,
m.first_name + ' ' + m.last_name manager
FROM
sales.staffs e
INNER JOIN sales.staffs m ON m.staff_id = e.manager_id
ORDER BY
manager;
Output as Below -
6) Cross Join :Cross join will return all the rows from both the tables and it is also called Cartesian join
Example If one table has 10 records and another table contain 5 records, then cross join will return total 50 row from cross join.