Examples of Natural Joins in Oracle Database

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

Natural Joins.

Definition:

A NATURAL JOIN is a JOIN operation that creates an implicit join clause for you based on the common columns in the two tables being
joined. Common columns are columns that have the same name in both tables.

A NATURAL JOIN can be an INNER join, a LEFT OUTER join, or a RIGHT OUTER join. The default is INNER join.
Source: Oracle

We will start with Natural Join. But before jumping over to natural join let me tell you a few terminologies

Source table: Table which comes after FROM clause in the select statement 

Target table: All the tables which come after JOIN clause in the query.

When the join query is executed then oracle starts matching data from the source table to the target table. If there is a hit for a matching
source table data in the target table then the value is returned. 

Examples of Natural Joins in Oracle Database


Scenario 1: When there is only one identical name column between source and target tables.  

Let’s use Departments table and locations table for the demonstration. 

Department table has 4 columns DEPARTMENT_ID, DEPARTMENT_NAME, MANAGER_ID, LOCATION_ID

And Locations table has 6 columns 


Location id, street address, postal code, city, state province and country id

Upon minutely observing you will notice that location id is a common column between our source and target tables. It is the foreign key and
thus has same data type and column width. Let’s write the query for natural join. 

Say you want to find the City for all your Departments 

SELECT   department_name, city   FROM   departments   NATURAL JOIN   locations;

In this query we are selecting department name from departments table and city from locations table. You can select other columns too

Departments is our source table as its coming right after FROM keyword and locations is our Target table as its coming after JOIN clause. 

The best part of using Natural join is that you do not need to specify the join column because column with the same name in source and
target table are automatically associated with each other. 

On executing this query oracle returns all the rows from department column of departments table and from city column of locations table,
where location id of departments table is equal to the location id of location table. 

Scenario 2: What if when our source and target tables have more than one identical name column.

To demonstrate this scenario we will use employees and departments table these two tables shares two common columns which are
department id and manager id.

Here if we put Natural join on these two tables then oracle engine will use these two common columns to return the result.

Say we want to see the name of employee and the name of department in which he or she is working. For that we will select first name from
employee table which is our source table and department name from departments table.

SELECT   first_name, department_name   FROM   employees   NATURAL JOIN   departments;


As I have already mentioned that when we use natural join, there is no need to specify join columns explicitly. All the columns which are
common in both source and target table get associated automatically.

The queries in which all the common columns of source and target table get associated automatically are known as Pure Natural Join.

Which means in this query, oracle has automatically associated our common columns which are department id and manager id.

To help you understand more clearly let’s write same query but this time using ON clause.

SELECT   first_name,department_name   FROM   employees  JOIN    departments   ON   (employees.manager_id =


departments.manager_id   AND   employees.department_id = departments. department_id);

Here is a slight change in the natural join syntax as we are using ON clause this time, instead of writing natural join we will only write JOIN.

Both these queries produce the same results as both are same query written in different ways.

In this query we emphasize natural join using ON clause. As we are using ON clause thus it becomes mandatory to specify the columns over
which we want to perform the join.

Scenario 3: Natural join with USING clause

Here Once again we will use our natural join query.

SELECT   first_name, department_name   FROM   employees    NATURAL JOIN   departments;

As we can see here in this query that when we have more than one common column oracle engine uses all of them to produce the result

Now, here in this query we are using employees and department tables which have 2 common columns department id and manager id. 

What if you want to use only department id in your natural join instead of both manager and department id? 

In this situation we use natural join with USING clause. 

Say we want to select all the first name and department name from source table employees and target table departments from where we
have equal values of manager ids in both the employees table and the departments table. 

Let’s write the query

SELECT   first_name, department_name   FROM   employees   JOIN   departments   USING(manager_id);

I hope you enjoyed reading.

Help me by sharing this article with your friends and on your social media. And subscribe to my YouTube channel for Oracle/SQL tutorials.

Thanks.

Cross Join In SQL.


Hey guys hope you are enjoying my articles. This one is all about cross outer join
Definition

Cross Join produces   Cartesian product of the tables which are participating in the Join queries that’s why it’s also known by the name of
Cartesian Join.

Generally we use CROSS JOIN when there is no relationship between participating tables.
Syntax

SELECT  column names  FROM  table1  CROSS JOIN  table 2  WHERE (expression)  ORDER BY  column names;  

Or

SELECT  column names  FROM  table1,  table 2  WHERE (expression)  ORDER BY  column names  

In the first line we have our Select statement where you can specify the list of columns from both the participating tables.  

In the second line we have our tables and the CROSS JOIN clause. Here you can write either Cross Join or just put a comma in between the
names of both tables. 

Also with cross join we do not have any ON or USING join condition. But you may, however, specify a WHERE and ORDER BY clause.

Note if you are using ORDER BY clause then make sure it must be the last statement of your SQL query.

Example:
I’ll be using the same table which we have been using in all our JOIN tutorial so far. These are the emp and dept tables.
(For tables you can refer to Table for SQL Joins tutorial)

Query 1: CROSS JOIN

SELECT  emp_name, dept_name  FROM  emp  CROSS JOIN  dept;

This query is fairly simple; we are selecting emp name and dept name from emp and dept tables respectively. 

On executing this query, the first record of emp name column of emp table that is – Steve, gets paired with all the rows of the second table
dept. Similarly second record Nancy gets paired with all the rows of dept table and so on. 

Since this cross join produces a Cartesian product therefore the total number of rows in the result will be equal to total number of rows in
table 1 multiplied by total number of rows in table 2.  

Since in our case we have total 5 rows in each table thus total number of rows in our result is 25.

Query 2: CROSS JOIN with WHERE clause.

Say you want to see only those records where dept name is IT. 

SELECT  emp_name,dept_name  FROM  emp  CROSS JOIN  dept  WHERE dept_name = 'IT';
On execution this query will return all the emp name which are corresponding to Department name IT

Query 3 : Cross Join with Order By clause

Similarly you can use ORDER BY clause if you want to sort the result returned by your query in Ascending or Descending order.

NOTE: Here ORDER BY clause must be the last statement of a QUERY.

ORDER BY clause by default sorts the result in ascending order. But if you want to arrange the result in Descending order then you have to
specify it by using DESCENDING or DESC keyword with the ORDER BY clause.

SELECT  emp_name,dept_name  FROM  emp  CROSS JOIN  dept  WHERE dept_name = 'IT'  ORDER BY emp_name;

And if you want to reverse the order meaning if you want to sort the result in Descending order, then you just need to add DESC or
DESCENDING keyword after the column name of ORDER BY clause

SELECT  emp_name,dept_name  FROM  emp  CROSS JOIN  dept   WHERE dept_name = 'IT'  ORDER BY emp_name  DESC;

In this tutorial I try to sum up all the concepts of CROSS JOIN hope you enjoyed reading.

Do share this article with your friends on social networking. You can also watch my video for the same. Thanks! 

Inner Join In SQL.


This is the fifth tutorial in the Join series and till now we have seen Natural Join, Right Outer Join, Full Outer Join and left Outer Join.
And in this tutorial we will cover the concepts of INNER Join. 

Definition
Inner Join is the join which returns all those rows from both the participating tables that satisfy the Join condition or for that matter expression
of ON/USING clause.  

Syntax

SELECT column names FROM   

table1 INNER JOIN / JOIN table 2  

ON(expression) or USING(column_name)  

WHERE(expression) ORDER BY column names;  


In the first line of our syntax we have our SELECT statement where you specify all those columns from both the participating table (table1
and table2) whose data you want to fetch in your result set. The SELECT statement is followed by  FROM keyword.

In the second line of our syntax we have our JOIN clause which is INNER join as obvious. You can either write INNER JOIN or simple JOIN
as both are permissible and perform the same task. On both side of our Join clause we have our tables which are TABLE 1 and TABLE 2.

Followed by our join clause we have our Join condition. Basically we have two types of join condition that we can use one at a time but
never together. These two join conditions are ON and USING. Usage of each join condition depends on certain conditional parameters. 

And at the end of the syntax we have our WHERE and ORDER BY clause. 

*Note here if you are using ORDER BY clause then it must be the last statement of your query.

When to use ON and USING clause

Hope syntax is clear.

Let’s do some practical exercise. I’ll be using the same table which we have been using in all our JOIN tutorial emp and dept.
(for tables you can refer to Table for SQL Joins tutorial)

QUERY 1: INNER JOIN with ON clause

SELECT emp_name,dept_name FROM emp INNER JOIN dept ON(emp.EMP_ID = dept.EMP_ID);

Here in this query we are selecting emp name from emp table and dept name from dept table while in JOIN condition which in this case is
the ON clause we are comparing emp_id column of both the tables.

As here in this query we are using ON join condition thus we can use any column as expression of ON clause as long as columns share
same data types. The name of the column doesn’t matter here.

For example we have dept_id column in dept table which shares same data type as of emp_id column of emp table which is a NUMBER thus
here in our ON clause we can use this dept_id column too.

SELECT emp_name,dept_name FROM emp INNER JOIN dept ON(emp.EMP_ID = dept.DEPT_ID);

QUERY 2: INNER JOIN with USING clause.

We already know that we can use USING clause when the column in join condition share same name and same data type and are compared
only using equal to ( = ) comparison operator and no other comparison operator such as greater than, less than etc.

SELECT emp_name,dept_name FROM emp INNER JOIN dept USING(EMP_ID);

Here we used emp_id column in USING clause because it’s common in both tables (foreign key relation in emp and dept table) and shares
same name as well as data type. We can easily compare its value using equal to operator in both the tables as we did in our first query
where we used emp_id column of both the tables in the expression of ON clause.
QUERY 3: INNER JOIN with WHERE clause.

We use WHERE clause to limit the result of a Query, similarly you can use WHERE clause here with Inner join to do the same. Say you want
to see the name and departments of only those employees who have a salary of less than 50000 For that you just have to add the where
clause right after the JOIN condition in the query. 

For example 

SELECT emp_name,dept_name FROM emp INNER JOIN dept USING(EMP_ID) WHERE emp.emp_salary < 50000;

QUERY 4: INNER JOIN with ORDER BY clause.

Feel free to use ORDER BY clause if you want to sort the result returned by your query in Ascending or Descending order.

NOTE here ORDER BY clause must be the last statement of a QUERY.

ORDER BY clause by default sorts the result in ascending order. But if you want to arrange the result in Descending order then you have to
specify it by using DESCENDING or DESC keyword with the ORDER BY clause.

For example 

1. Sort the result in ascending order according to emp_name column

SELECT emp_name,dept_name FROM emp INNER JOIN dept USING(EMP_ID) ORDER BY emp_name;

2. Sort the result in descending order according to emp_name column.

SELECT emp_name,dept_name FROM emp INNER JOIN dept USING(EMP_ID) ORDER BY emp_name DESC;

In this tutorial I try to sum up all the concepts of INNER JOIN hope you enjoyed reading.

Full Outer Join In SQL.


Today’s SQL article is all about Full Outer Join.

Before moving ahead just want to say that in order to better understand the concept of full outer Join please read my last two SQL tutorial
article on right and left outer join.

Here once again we will be using same table which we have used so far in this Outer Join series. These are the emp and the dept tables.
Let’s have a quick look of the structure and the data of these two tables. 
Desc emp;  
Our table emp has 3 columns emp id, emp name
and emp salary. Here column emp id is a primary key.

Desc dept;  
Table dept also has 3 columns dept id, dept name
and emp id. Here in this table column dept id is a primary key where column emp id is a foreign key reference from the emp table.

Now let’s have a look at the data of these two tables.


SELECT * FROM emp;  
Emp table has 5 rows where column one has emp
id and column 2 has emp name and column 3 consist the salary of these employees.

Now data of dept table


SELECT * FROM dept;  
Table Dept also has 5 columns. Column one
hold dept id where column two has dept name and column three emp id which is the foreign key has only 3 records corresponding to
department name sales account and finance. 

We can interpret this data easily. For example the employee with employee id 1 is named Steve in our emp table and works in department of
Sales. Similarly employee with employee id 2 is Nancy who works in Accounts department and employee with employee id 3 is Guru who
works in finance. Also we have not assigned any employee id for department of IT and Marketing which signifies that no one works in these
departments.

Let’s jump over to full outer join. 


Full outer join is kind of a combination of both right outer join and left outer join because it returns all the rows from left as well as
the right side table.

Let’s have look of FULL OUTER JOIN syntax.


Syntax
SELECT column names FROM   

table1 FULL   OUTER JOIN / FULL JOIN table 2

ON(expression) or USING(column_name)   

WHERE(expression) ORDER BY column names;  

Syntax is pretty similar to our left or right join as you can see. We have our SELECT statement where you can specify the name of the
columns from both the participating tables followed by FROM clause. And our JOIN clause which is full outer join. Here you can either write
full outer join or just outer join since both are permissible and perform the same task. And then we have our Join condition ON and USING
followed by WHERE and ORDER BY clause.

Query 1 : Full Outer Join With ON clause


SELECT   emp_name, dept_name   FROM   emp   FULL OUTER JOIN   dept   ON  (emp.emp_id  =  dept.emp_id);

Here in this query we are selecting emp name column from emp table and dept name column from dept table. In our full outer joinclause we
have emp table on left side and dept table on right side and then we have Our ON clause where we are comparing the values of emp id
columns from the both the tables.

On executing this query the result will be.

If you will observe minutely then you can see that the result till row 5 is similar to that of  right outer join, As all the records from right side
table is here and only those records from left side table which satisfy the join condition are here in the result. Followed by all the remaining
records from the tables thus the last row 6 and 7 contains the remaining emp names.

Here in this ON join clause we used columns which have same name and data type. Now let’s use columns which have different name and
same data type for example column
dept id.
SELECT   emp_name, dept_name   FROM   emp   FULL OUTER JOIN   dept   ON  (emp.emp_id  =  dept.dept_id);

and the result of this query is


Query 2 : Full Outer Join With USING clause
We use USING join condition when

The column in join condition share the same name and same data type and are compared only using = comparison operator and no other
comparison operator such as greater than, less than etc. 

As you can see, in the join condition (ON clause) of Query 1 we have used emp id column of both the tables. This column shares the same
name and same data type hence we can easily replace this ON clause with USING clause. Let’s do it. 

SELECT   emp_name, dept_name   FROM   emp   FULL OUTER JOIN   dept   USING  (emp_id);

The result of this query is 


If you compare this result with the result of our first query then you will find them as exactly the same. 

Query 3 : Full Outer Join With WHERE clause


You can also limit the result by using WHERE clause. Say you want to see the name of only those employees and their departments who
have a salary of less than 50000

For that we can modify our query 2 and add a where clause to it.

SELECT   emp_name, dept_name, emp_salary   FROM   emp   FULL OUTER JOIN   dept   USING  (emp_id) 
WHERE emp.emp_salary < 50000;

On executing this query you will get only those employee and their departments who has salary less than 50,000 
Query 4 : Full Outer Join With ORDER BY clause
Similarly you can sort the result using ORDER BY clause. Say you want to sort the result of query 3 in ascending order according to the
employee name (emp_name column) For that just add the ORDER BY clause followed by the column name which is emp_name in our
case. 

SELECT   emp_name, dept_name   FROM   emp   FULL OUTER JOIN   dept   USING  (emp_id)  
WHERE emp.emp_salary < 50000  ORDER BY emp_name;

If you execute this query then by default the result will be sorted in ascending order. 
If you write DESC right after the column, your result will be sorted in descending order. For Example 

SELECT   emp_name, dept_name   FROM   emp   FULL OUTER JOIN   dept   USING  (emp_id)  
WHERE emp.emp_salary < 50000   ORDER BY emp_name DESC;

That’s it on Full Outer Joins. If you found it useful then please share it with your friends on social networking. You can also write to me for
any queries. Keep reading for more such concepts. 

Right Outer Join In SQL.


As the name suggests Right Outer Join is a form of Outer Join that returns each and every record from the source table and returns only
those values from the target table that fulfil the Join condition.

*Note: The Source table is the one situated on the right side of the Right Outer Join Clause whereas  The Target table is the one on the left
side of this clause.

Syntax :
SELECT   
columns     
FROM   
  target_table RIGHT OUTER JOIN source_table 
ON(source_table.column = target_table.column)  
WHERE condition  
ORDER BY column_names;  
Examples:
To demonstrate the working of Right Outer Join, I have created two tables by the name of  emp and dept and have also inserted some data
in them. 

Structure of emp table


Structure of dept table

Data In emp table


Data In dept table

Query 1: Right Outer Join with ‘ON’ clause


Now when should we use ON Join Condition in SQL Joins you ask?

1. When columns which are participating in ON join condition have Different name and Same Data type or
2. When columns which are participating in ON join condition have SAME NAME and SAME Data-type.

Let’s write a very simple Right outer join query.

SELECT 
dept_name emp_name,  
emp RIGHT OUTER JOIN  dept  FROM
ON (emp.EMP_ID = dept.EMP_ID);

In the above query we are selecting emp_name from emp table and dept_name from dept table. Emp table is the source tableas it’s on
the right hand side of join clause thus automatically making dept table as the target table.

Column emp_id is a primary key in emp table and foreign key in dept table thus column emp_id is the column which is establishing a
relationship in between these two tables. As column emp_id is common in both tables thus it’s a best fit for Join condition (ON clause).

If you execute this query you will get all the rows of emp_name column of emp table as emp is the source table and only those rows of
dept_name column of dept table which satisfy the join condition (condition in ON clause).
Query 2: Right Outer Join with WHERE clause
You can use WHERE clause with any type of JOIN and limit or Filter the result. In case of JOINS, WHERE clause always comes after Join
Condition (ON or USING) Say you want to see employees name and department name whose salary is less than 50,000 

dept_name emp_name,  SELECT  
emp RIGHT OUTER JOIN  dept  FROM  
emp_salary (emp.EMP_ID = dept.EMP_ID) WHERE  ON < 50000; 

Query 3: Right Outer Join with USING clause


Using clause can be used on the place of ON clause when

1. We are performing Equi Join.


2. We want to put join on that column of source and target table which are common i.e. have same name and data type.

Most of the joins you’ll perform will be equijoins, and if you always use the same name as the primary key for your foreign keys, then:
USING (emp_id)  emp RIGHT OUTER JOIN dept  FROM  emp_name,dept_name  SELECT

Introduction of Joins In SQL.


Joins In SQL

Whenever we want to fetch data from two or more database tables based on common field (column) we use Joins. 
DEF:
Technically   Joins are SQL operations which help us in retrieving data from two or more tables that share a common
field.  

Types of Joins
There several Types of Joins such as

1. Inner Join
2. Outer Join
3. Cross Join
4. Self-Join

Outer Join can further be categorize into 3 more categories

1. Right Outer Join


2. Left Outer Join
3. Full Outer Join.
Apart from types of join we also have two join conditions these are

1. Equi Joins
2. Non-Equi Joins

Equi Join: this type of Join looks for common records in two tables on the basis of equality condition and then combines them. Equi-Join is
constructed with the help of equality operator (=) where the values of Primary key and Foreign key are compared. Hence the common or
matching records from the two tables are presented in the result.

Non Equi Join: Here equality operator is not used, instead operators such as <, >, BETWEEN etc. are employed. Therefore Non Equi-Join
is the opposite of Equi-Join, and uses joining conditions excluding equal operator. For example, in a non Equi-Join condition you can use !=,
<=,>=,<,> or BETWEEN etc. operators can be used for joining. For implementation you can see Inner-Join.

Outer Join: Outer joins are the SQL operation which definitely return all the rows from Source table no matter whether there is a matching
join condition hit or not. At the same time it returns only those rows of the target table that fulfils the matching join condition otherwise just
shows ‘null’ in the rows

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy