Friday, July 18, 2008

How To Join Tables? Learn From These Simple Instances Below

We have a couple of Tables below. See what would happen if we do inner join and outer join. See the result...

A. ----Table 1----- Table 2
----------1 ------------ 1
----------2 ------------ 2
----------3 ------------ 4
----------5 ------------ 5
----------8 ------------ 6
----------9 ------------ 7
---------11 ------------ 8
---------12 ----------- 10
---------13 ------------ 11


B. ----Table 1 ----------Table 2
---------SSN --------------- SSN
-----Last_Name -------- Apt #
-----First_Name --------Street
---------Age ----------------City
------------------- ---------- Zip


Inner Join:
Joining two tables by giving cause of equality is known as Inner Join. Only matching records from both tables get displayed.

In Inner Join only these numbers 1, 2, 5, 8, 11 will be displayed.

Inner Join: SQL> select a.SSN, a.Fname, b.city, b.zip from Table1 a, Table2 b
where a.SSN = b.SSN;

Outer Join:
Joining two tables to get matching records from both and non-matching records from any one of them is known as Outer Join.

Left Outer Join:
In this join 1, 2, 3, 5, 8, 9, 11, 12, 13 will be displayed.

Right Outer Join:
In this join 1, 2, 4, 5, 6, 7, 8, 10, 11 will be displayed.

Outer Join:
SQL> select a.SSN, a.Fname, b.city, b.zip from Table1 a, Table2 b
where a.SSN (+) = b.SSN;

No comments: