Home Tutorial Java Jdbc Joining two tables using Natural right join

 
 

Joining two tables using Natural right join
Posted on: June 3, 2010 at 12:00 AM
In Natural Right join, both table are merge to each other according to common field, but the priority is given to the Second table's field values.

Join Table with Natural Right join

In Natural Right join, both table are merge to each other according to common field, but the priority is given to the Second table's field values  means a Right join returns all the values from the right table and matched values from the left table (NULL in case of no matching join predicate).

In Right join, every row of left table appears at least once in joined table, If no matching row from the "Left" table exists, NULL will appear in columns from Left Table for those records that have no match in Right Table.

Query for Right Join

SELECT *FROM employee NATURAL RIGHT JOIN Emp_sal

 

The two tables before Right join --

"employee" table   

Emp_code  Emp_name
1642 ankit
1643 rahul
1644 rahul

 "emp_sal" table

Emp_code Empsalary Emp_designation
1642 4 lakhs PROJECT LEADER
1643 3 lakhs PROJECT MANAGER
1644 2.5 lakhs PROGRAMMER

natrightjoin.java

import java.sql.*;

public class natrightjoin{
  public static void main(String[] args) {
    System.out.println("NATURAL RIGHT JOIN");
    Connection con = null;
    try{
      Class.forName("com.mysql.jdbc.Driver");
      con = DriverManager.getConnection("jdbc:mysql://192.168.10.13:3306/ankdb","root","root");
      try{
        Statement st = con.createStatement();
        ResultSet res = st.executeQuery("SELECT *FROM "+"employee"+" NATURAL RIGHT JOIN "+"emp_sal"); 
        //Natural Right Join two tables
        System.out.println("Emp_code" + "\t" + "Emp_name" + "\t" + "Emp_salary"+"\t"
 +"Emp_designation");
    while(res.next()){
    int code = res.getInt("Emp_code");
    String name = res.getString("Emp_name");
    String sal = res.getString("Emp_salary");
    String post = res.getString("Emp_designation");

    System.out.println(code + "\t\t" + name + "\t\t" + sal+"\t\t"+post);
    }
      }
      catch (SQLException s){
      System.out.println("SQL statement is not executed!");
      }
    }
    catch (Exception e){
    e.printStackTrace();
    }
  }
}

 OUTPUT

C:\Program Files\Java\jdk1.6.0_18\bin>java NatJoin
Table after Natural Join
Emp_code        Emp_name     Emp_salary          Emp_designation
1642                ankit               4 lakhs                 PROJECT LEADER
1643                nitesh              3 lakhs                 PROJECT MANAGER
1644                rahul               2.5 lakhs              PROGRAMMER

Download Example's code

Related Tags for Joining two tables using Natural right join:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.