SQL JOINS
We are discus in detail how many types of SQL Joins so let's get start.
1. INNER JOIN: Returns rows when there is a match in both tables.
The INNER JOINS creates a new results table by combing column values of two tables(table A, table B) based upon the join – predicate.
The query compares each row of table1 with each rows of table2 to find all pairs of rows which satisfy the join predicate.
Command of INNER JOIN: -
select e.Emp_id, e.E_fname,e.E_lname,
d.dept_id, d. dept_name
from employee e
inner join department d
on e.dept_id=d.dept_id;
2. LEFT JOIN: Returns all rows from the left tables, even if there are no matches in the right table.
- The LEFT JOIN return all the values from the left table, plus matched values from the left side table or NULL in case of no matching join predicate.
Example:
select e.Emp_id, e.E_fname, e.E_lname, e.E_salary,
d.dept_id, d.dept_name
from employee e
left join department d
on e.dept_id=d.dept_id;
Result of LEFT JOIN:
3. RIGHT JOIN : Returns all rows from the left tables, even if there are no matches in the left table.
The RIGHT JOIN return all the values from the Right table, plus matched values from the left side table or NULL in case of no matching join predicate.
Syntax: -
select e.Emp_id, e.E_fname,e.E_lname,e.E_salary,
d.dept_id, d.dept_name
from employee e
right join department d # Change this line here
on e.dept_id=d.dept_id;
Result of RIGHT JOIN:
4. FULL OUTER JOIN: Return rows when there is a match in one of the tables.
- The FULL OUTER JOIN combines the results of both left and right outer joins. The Joined tables contains will all records from both the tables and fill in NULLs for missing matches on either side.
select e.Emp_id, e.E_fname,e.E_lname,e.E_salary,
d.dept_id, d.dept_name
from employee e
left join department d #step 1 add left join
on e.dept_id=d.dept_id
union #step 2 add union methods
select e.emp_id,e.e_fname, e.e_lname, e.E_salary, d.dept_id, d.dept_name
from employee e
right join department d #step 3 add right join
on e.dept_id=d.dept_id;
Result of FULL OUTER :
5. SELF JOIN: Used to join a table to itself as if the tables were two tables, temporally at least one tables in the SQL statements.
- Definition : Assume there are 4 records in table1 and 3 records in table 2 find cross joins methods.
Select *from table1 CROSS JOIN table2;
Explanation of Cross Join : It is just like that multiple into 1 to all (SET- THEORY).
Example : Lets see an Example of Employee and Department value of CROSS JOIN
Table 1* Table2
Command : select *from department cross join employee;
OUTPUT:-
6. CARTESIAN JOIN[CROSS JOIN] :- Returns the Cartesian product of the set of records from the two or more joined tables.
this is end of the course and this is just basic we are discuss in details full so follow me in details.
0 Comments