You are on page 1of 17

Joins

• When we normalize data and create tables inside database, the data
is scattered into different tables. In order to create meaningful data,
we must query data by joining multiple tables. 

• This is where joins comes into picture. Using join syntax, we join two
or more tables to create reports.
• A join will always happen only on key columns!
A join is a query that combines rows from two or more tables. For
joining, you must have:
• Two or more tables
• A join condition
Tables : We have
two tables, Book
table and member
table
Types of joins

• INNER JOIN There are two ways :


• NATURAL JOIN
• OUTER JOIN
• LEFT OUTER JOIN
Using traditional SQL syntax
• RIGHT OUTER JOIN Using JOIN types inside your query
• FULL OUTER JOIN
We are trying to return the MEMBER_NAME and the CATEGORY of book
borrowed. In this case we will join both tables using the BOOK_ID
column:
TRADITIONAL METHOD
In a traditional join method, we specify all join tables under FROM clause and join
column under WHERE clause.

Carefully watch the join


condition. It says, return the
rows where book_id column
values are matching from
members and books tables

If you observe the output, we have only the rows from


both table where MEMBERS.BOOK_ID is same as
BOOKS.BOOK_ID. Note the CATEGORY column is null
for member KISH.
NATURAL JOIN

• In a perfect relational database, DBMS is aware of how tables are


joined and what are the key columns. When you joining two tables
and do not want to specify the joining column, use NATURAL….JOIN.
DBMS will join tables automatically for you on the key columns.
OUTER JOIN
• It returns rows that satisfy the join condition and also some/all  the
rows that do not satisfy the condition.
There are three types of OUTER JOIN:
• LEFT OUTER JOIN
• RIGHT OUTER JOIN
• FULL OUTER JOIN
Observe that we got all the rows as output from the
MEMBERS table because its on the left side of the
JOIN keyword. We also have output from the
BOOKS table (which is on the right side of the JOIN
keyword).

In the output all records from MEMBERS table are


present in the output as all satisfy the join
condition. As we do not have any record in the
MEMBERS table that do not satisfy the JOIN
condition, hence no null values.
Observe the output , we have all the records from tabl
BOOKS (which is on the right side of the JOIN keyword
and only the matching records from the MEMBERS
table (which is on the left side of the JOIN keyword).

For all the non matching values from MEMBERS table,


NULL value is returned.
Notice that we have all the records from both MEMBERS
table and BOOKS table. And where ever the values are not
matching, NULL is returned.

You might also like