TSO-ISPF JCL COBOL VSAM DB2 CICS Tools Articles Job Portal Forum Quiz Interview Q&A

DB2 - SQL JOIN Clause


A JOIN clause is used to combine rows from two or more tables, based on a related column between them.

A join is a mechanism used to associate tables within a SELECT statement.

For creating a join, you must specify all the tables to be included and how they are related to each other.

Let's look at the "Orders" table data below:

OrderidCustomernumberOrderdate
1001102020-09-08
1002992020-09-01
1003172020-08-25
1004762020-09-19

Let's look at the "Customers" table data below:

CustomernumberCustomernameCountry
76JackAmerica
17JancyGermany
10RobertIndia
99BrianChina

Notice that the "Customernumber" column in the "Orders" table refers to the "Customernumber" in the "Customers" table. The relationship between the two tables above is the "Customernumber" column.

Let us see how to create SQL statement that selects records that have matching values in both tables.


Example:

SELECT Orders.Orderid, Customers.Customername, Orders.Orderdate
  FROM Orders
  INNER JOIN Customers ON Orders.Customernumber=Customers.Customernumber;

Result:

OrderidCustomernameOrderdate
1001Robert2020-09-08
1002Brian2020-09-01
1003Jancy2020-08-25
1004Jack2020-09-19

Explanation:

The SELECT statement starts in the same way as all the statements you have looked at so far, by specifying the columns to be retrieved. The big difference here is that two of the specified columns (Orderid and Orderdate) are in one table, whereas the other (Customername) is in another table.

Unlike all the prior SELECT statements, this one has two tables listed in the FROM clause, Orders and Customers.

You must use the fully qualified column name (table and column separated by a period) whenever there is a possible ambiguity about which column you are referring to. In this case, you specify Orders.Orderid and Customers.Customername.


Types of Joins:

There are two types of joins:

  • Inner Join - Retrieve matching values in both tables.

  • Outer Join - Retrieve all records from the left table, and the matched records from the right table.

    1. Left Outer Join - Retrieve all records from the left table, and the matched records from the right table.

    2. Right Outer Join - Retrieve all records from the right table, and the matched records from the left table.

    3. Full Outer Join - Retrieve all records from both table.

We will see each type of joins in next chapter...


If you have any doubts or queries related to this chapter, get them clarified from our Mainframe experts on ibmmainframer Community!

Are you looking for Job Change? Job Portal