Sei sulla pagina 1di 9

Joins

1. Inner Join
2. Outer Join
o Left Outer Join
o Right Outer Join
o Full Outer Join
3. Cross Join

Joins in SQL Server allows the retrieval of data records from one or more tables having some relation
between them. Logical operators can also be used to drill down the number of records to get the
desired output from sql join queries.

Inner Join: Inner Join is a default type join of SQL Server. It uses logical operators such as = ! " to
match the records in two tables. Inner Join includes equi join and natural joins.
Examples:
SQL Inner Join Examples
Eui Join: #qui Join returns all the columns from both tables and filters the records satisfying the
matching condition specified in Join !O"# statement of sql inner join query.
SQL Inner Eui Join Example:
$S# %&'()*I%+
S#L#,( - .'&/ ,0(#1&'I#S , I%%#' J&I%
2'&+$,(S 2 &% 2.,0(#1&'3I+ = ,.,0(#1&'3I+

'esult will display the following columns4
Categor$I% ,ategory%ame +escription 2icture 2roductI+ 2roduct%ame SupplierI+ Categor$I%
Quantity2er$nit $nit2rice $nitsInStoc5 $nits&n&rder 'eorderLevel +iscontinued
0bove equi join sql query will display the categoryId two times in a row because both the tables have
categoryId column. 3ou can convert the result into natural &oin by elimination the identical columns
and unnecessary columns.
In the previous article you learnt how to use equi inner join in sql queries to join two tables and
retrieve the combined result of both sql database tables. See the e6ample of equi join here7 SQL
Inner Eui Join Examples. %otice that equi join sql query returned the categoryId column twice
because of relation between two tables. 2roducts table also has categoryId column that shows the
product belongs to a particular category in categories whose categoryId is also saved in products table
as a relational 5ey between both the tables.
"atural &oin uer$ example:
S#L#,( ,.- 2.2'&+$,(I+ 2.2'&+$,(%0/# .'&/ ,0(#1&'I#S ,
I%%#' J&I%
2'&+$,(S 2 &% 2.,0(#1&'3I+ = ,.,0(#1&'3I+

(his natural join query will return all the columns of categories table and prodcutId and product%ame
from products table.

3ou can further modify this natural inner join query as per your requirements to visuali8e the data by
specifying the column names of categories table also.

Inner Join Quer$ Example '$ spe(if$ing (olumn names:
S#L#,( ,.,0(#1&'3I+ ,.,0(#1&'3%0/# 2.2'&+$,(I+ 2.2'&+$,(%0/# 2.$%I(2'I,# .'&/
,0(#1&'I#S , I%%#' J&I%
2'&+$,(S 2 &% 2.,0(#1&'3I+ = ,.,0(#1&'3I+

(his inner join query will display only the specified column names of both the tables.
#qui Join 9Inner Join: for combining the columns of two sql database tables into single table output
result. (ry sl inner eui &oin examples.

%atural Join 9Inner Join: for getting the output of equi join into the specified columns format and
removing the ambiguous column names from the output. See sl inner natural &oin examples.

SQL Inner Join uer$ )ith *+, operator:

S#L#,( ,.,0(#1&'3I+ ,.,0(#1&'3%0/# 2.2'&+$,(I+ 2.2'&+$,(%0/# 2.$%I(2'I,#
.'&/ ,0(#1&'I#S , I%%#' J&I%
2'&+$,(S 2 &% 2.,0(#1&'3I+ = ,.,0(#1&'3I+
*)#'# 2.$%I(2'I,# = ;<
&'+#' =3 ,.,0(#1&'3%0/# 2.2'&+$,(%0/#

(his inner join query will return the categoryid categoryname productid productname unitprice
where product unit price = ;<

SQL Inner Join Quer$ )ith *-, operator:

S#L#,( +IS(I%,( ,.,0(#1&'3I+ ,.,0(#1&'3%0/#
.'&/ ,0(#1&'I#S , I%%#' J&I%
2'&+$,(S 2 &% ,.,0(#1&'3I+ " 2.,0(#1&'3I+
*)#'# 2.$%I(2'I,# = ;<
&'+#' =3 ,.,0(#1&'3%0/#

(his inner join query will return the categoryId category%ame having products with unit price=;<

SQL Inner Join Quer$ )ith not eual *.-, operator:

S#L#,( +IS(I%,( 2;.2'&+$,(%0/# 2;.$%I(2'I,# 2;.S$22LI#'I+
.'&/ 2'&+$,(S 2; I%%#' J&I% 2'&+$,(S 2>
&%
2;.S$22LI#'I+=2>.S$22LI#'I+
0%+ 2;.$%I(2'I,#!"2>.$%I(2'I,#
*)#'# 2;.$%I(2'I,# ! >< 0%+ 2>.$%I(2'I,# ! ><
&'+#' =3 2;.S$22LI#'I+

Inner Join with not equal operator is rarely used in self joins. 0s an e6ample above sql self join query
returns the productname unitprice supplierid where suppliers having > or more than > products with
unit price less than ><.
Outer Join: &uter Join has further ? sub categories as left right and full. &uter Join uses these
category names as 5eywords that can be specified in the .'&/ clause.
o Left Outer Join: Left &uter Join returns all the rows from the table specified first in
the Left &uter Join ,lause. If in the left table any row has no matching record in the
right side table then that row returns null column values for that particular tuple.
#6amples4
Inner joins return only those rows from both sql database tables having matching records in both
the tables whereas left outer &oin returns all the rows from the left table and related matching
records from the other one.

SQL Left Outer Join Example:

$S# 2$=S
S#L#,( 0.0$@.%0/# 0.0$@L%0/# 2.2$=@%0/#
.'&/ 0$()&'S 0 L#.( &$(#' J&I% 2$=LIS)#'S 2
&% 0.,I(3 = 2.,I(3
&'+#' =3 0.0$@L%0/# 0.0$@.%0/#

Result:

au/fname au/lname pu'/name
0braham =ennet 0lgodata Infosystems
'eginald
=lotchetA
)alls %$LL
,heryl ,arson 0lgodata Infosystems
/ichel +e.rance %$LL
Innes del ,astillo %$LL
0nn +ull %$LL
/arjorie 1reen %$LL
/orningstar 1reene %$LL
=urt 1ringlesby %$LL
Sheryl )unter %$LL
Livia Barsen %$LL
,harlene Loc5sley %$LL
Stearns /ac.eather %$LL
)eather /c=adden %$LL
/ichael &CLeary %$LL
Sylvia 2anteley %$LL
0lbert 'inger %$LL
0nne 'inger %$LL
/eander Smith %$LL
+ean Straight %$LL
+ir5 Stringer %$LL
Johnson *hite %$LL
05i5o 3o5omoto %$LL


(his left outer join query retrieves the author names and publisher name having same cities. )ere
all rows retrieved from the left table i.e. authors and publisher name having the similar city other
columns of pub@name column are null due to no match found in the right table.
o Right Outer Join: 'ight &uter Join is e6actly the reverse method of Left &uter Join.
It returns all the rows from right table and returns null values for the rows having no
match in the left joined table.
Examples:
SQL Right Outer Join Examples
In the previous article regarding sl left outer &oin we learnt left outer join that retrieves all the
results from left table and related matches from the right table where right table having no matches
displays the %ull value in the corresponding columns. ,onsider the same e6ample of authors and
publishers table of the e6isting database 2$=S of sql server ><<<.

*e used the following left outer join query4

S#L#,( 0.0$@.%0/# 0.0$@L%0/# 2.2$=@%0/#
.'&/ 0$()&'S 0 L#.( &$(#' J&I% 2$=LIS)#'S 2
&% 0.,I(3 = 2.,I(3
&'+#' =3 0.0$@L%0/# 0.0$@.%0/#

Just change the left 5eyword to right outer join in above e6ampleD you will get the reverse output of
left outer join in the form of right outer join.

SQL Right Outer Join uer$ Example:

S#L#,( 0.0$@.%0/# 0.0$@L%0/# 2.2$=@%0/#
.'&/ 0$()&'S 0 'I1)( &$(#' J&I% 2$=LIS)#'S 2
&% 0.,I(3 = 2.,I(3
&'+#' =3 0.0$@L%0/# 0.0$@.%0/#

Result:

au/fname au/lname pu'/name
%$LL %$LL %ew /oon =oo5s
%$LL %$LL =innet E )ardley
%$LL %$LL .ive La5es 2ublishing
%$LL %$LL 'amona 2ublishers
%$LL %$LL 111E1
%$LL %$LL Scootney =oo5s
%$LL %$LL Lucerne 2ublishing
0braham =ennet 0lgodata Infosystems
,heryl ,arson 0lgodata Infosystems

%otice the difference in the output of right outer &oin and left outer &oin. 'ight outer join returned
all the rows from right table as all publisher names and null values for the left table columns having no
match found in left tableFs au@fname and au@lname.
Full Outer Join: .ull outer join returns all the rows from both left and right joined tables. If there is
any match missing from the left table then it returns null column values for left side table and if there
is any match missing from right table then it returns null value columns for the right side table.
Examples:
SQL Full Outer Join Examples
(o retrieve all the records from left as well as right table unless the records have matching relations in
each row you can use SQL F0LL O01ER JOI".
3ou can consider the e6amples of last two articles about left outer &oin and right outer &oin in
which left outer join retrieves all records from the left table and as all records of right table in right
outer join along with null values for the columns having no matching records in any tuple. (o retain all
the records of left as well as right table along with null values for non matching rows displaying the
combination of results of left outer and right outer join .$LL &$(#' J&I% is the best solution.

SQL F0LL outer &oin example:

S#L#,( 0.0$@.%0/# 0.0$@L%0/# 2.2$=@%0/#
.'&/ 0$()&'S 0 .$LL &$(#' J&I% 2$=LIS)#'S 2
&% 0.,I(3 = 2.,I(3
&'+#' =3 0.0$@L%0/# 0.0$@.%0/#

Result:

au/fname au/lname pu'/name
%$LL %$LL =innet E )ardley
%$LL %$LL .ive La5es 2ublishing
%$LL %$LL %ew /oon =oo5s
%$LL %$LL Lucerne 2ublishing
%$LL %$LL Scootney =oo5s
%$LL %$LL 'amona 2ublishers
%$LL %$LL 111E1
0braham =ennet 0lgodata Infosystems
'eginald =lotchetA)alls %$LL
,heryl ,arson 0lgodata Infosystems
/ichel +e.rance %$LL
Innes del ,astillo %$LL
0nn +ull %$LL
/arjorie 1reen %$LL
/orningstar 1reene %$LL
=urt 1ringlesby %$LL
Sheryl )unter %$LL
Livia Barsen %$LL
,harlene Loc5sley %$LL
Stearns /ac.eather %$LL
)eather /c=adden %$LL
/ichael &CLeary %$LL
Sylvia 2anteley %$LL
0lbert 'inger %$LL
0nne 'inger %$LL
/eander Smith %$LL
+ean Straight %$LL
+ir5 Stringer %$LL
Johnson *hite %$LL
05i5o 3o5omoto %$LL

0bove output retrieved from the sql full outer join query is the e6act combination of both the left as
well as right join outputs.
Cross Join: ,ross join wor5s as a ,artesian product of rows for both left and right table. It combined
each row of left table with all the rows of right table.
SQL Cross &oin returns the output result as a Cartesian pro2u(t of 'oth 2ata'ase ta'les.
Let left table has ;< rows and right table has G rows then SQL ,'&SS Join will return ;G< rows
combining each record of left table with all records of right side table. ,onsider the following e6ample
of ,'&SS Join4

$S# 2$=S
S#L#,( 0$@.%0/# 0$@L%0/# 2$=@%0/#
.'&/ 0$()&'S ,'&SS J&I% 2$=LIS)#'S
&'+#' =3 0$@.%0/#

0bove cross join will return >? - G = ;GH results by multiplying each row of authors table with
publishers table.

SQL CROSS Join )ith 34ERE (lause
=y just adding the where clause with ,ross join sql query it turns the output result into inner join.

Example:

$S# 2$=S
S#L#,( 0$@.%0/# 0$@L%0/# 2$=@%0/#
.'&/ 0$()&'S ,'&SS J&I% 2$=LIS)#'S
*)#'# 0$()&'S.,I(3 = 2$=LIS)#'S.,I(3
&'+#' =3 0$@.%0/#

It will display only the matching results in both tables.
Result:
au/fname au/lname pu'/name
,heryl ,arson 0lgodata Infosystems
0braham =ennet 0lgodata Infosystems

Self Join
.or self join in sql you can try the following e6ample4
Create ta'le emplo$ees:
emp/i2 emp/name emp/manager/i2
; John %ull
> (om ;
? Smith ;
H 0lbert >
I +avid >
J /urphy I
K 2etra I

%ow to get the names of managers from the above single table you can use sub queries or simply the
self join.
Self Join SQL Quer$ to get the names of manager an2 emplo$ees:
select e;.emp@name CmanagerCe>.emp@name CemployeeC
from employees e; join employees e>
on e;.emp@id=e>.emp@manager@id
Result:
manager emplo$ee
John (om
John Smith
(om 0lbert
(om +avid
+avid /urphy
+avid 2etra
0n2erstan2ing the Self Join Example
In the above self join query emplo$ees table is joined with itself using ta'le aliases e1 an2 e2.
(his creates the two views of a single table.
from employees e; join employees e> on e;.emp@id=e>.emp@manager@id
)ere e.emp@manager@id passes the manager id from the >nd view to the first aliased e; table to get
the names of managers.
select * from authors
select au_id,au_lname,city from authors
INSERT INTO authors
(au_id,au_lname,au_fname,hone,address,city,state,!i,contractu"
#$%&ES (''(,)*irst+ol), )Second+ol),),,,,,,,,,),)),)),)tn),)-'''.),."
select * from authors /here au_lname li0e )1*irst1)
select * from authors /here city 2)oa0land) and state2)+$)
select * from authors /here city 2)oa0land) and state2)+$) and !i2),3-',)
select * from authors /here city 2)oa0land) or state2)+$) or !i2),3-',) order 4y
city desc
SE%E+T state , +O&NT(au_id" $s total *RO5 authors 67ERE state IN()&T), )+$)"
8RO&9 :; state
&9<$TE authors SET state 2 )TN),city2)+hennai) 67ERE !i 2 )-'''.)
select * from authors /here state2)tn)

Potrebbero piacerti anche