SQL Joins Notes
SQL Joins Notes
-- during inner join the column values which are not a part of any table(i.e
satisfying the join condition) are left out.
------------------
left join = inner join + any additional record that is left in the left table.
- ham tables ko join nahi kar sakte but still we need to fetch record from that
table then in that case cross join is what we have to use.
=the ouput or the result set we are getting from the inner join will be used by
cross join to join the company.
-----------------
-- NATURAL JOIN
in this join , based on which column the join should happen will be decided by sql
itself.
- it will look for the column that are sharing the same name,and based on that it
will join the tables.
-- in sql a natural join will do inner join ,the columns that are sharing the same
name between the tables.
-- and in sql natural join will behave like cross join , if it doesn't find any
column that share the same name between columns
-- and let say if there are more than one column which is sharing the same name
between the tables then the join will happen on all of those column which are
sharing the same name.
-- and this is major difference between inner join and natural join as it is always
recommended to use inner join as compare to natural join because in natural join we
are giving control to the sql to choose the columns based on which tables should
joined , and as a dev we should be avoiding this.
-- using natural join can result into unexpected result if the matching column
names contain different values or the matching column is present with a different
name in table , which will create issue if our query is running in production
environment.
--------------------------
alter table department rename column dept_id to id;
-------------------
-- SELF JOIN
- inner ,left,right and self joins are the most widely used joins.
- self join is like when we are joining table to itself. ok so whenever there's a
req where we have to match one record from a table ,based on some another record of
that same table.
-- Write a query to fetch the child name their age corresponding to their parent
name
- So in this we have to use the same table twice.
--------------------------
select child.name as chid_name , child.age as ahild_age, parent.name as
parent_name, parent.age as parent_age from family as child join family as parent on
child.parent_id = parent.member_id;
---------------------------
- ham self join ko left , and right join ke sath bhi use kar sakte hai , so if we
use it with left join it will return basically all the child which doesn't have any
parent.
- and similarly for right join as well