SQL JOIN - Left outer join


Volta a página anterior

Volta ao Menu Principal


Desenvolvido por DORNELLES Carlos Alberto - Analista de Sistemas - Brasília DF. - cad_cobol@hotmail.com

SQL - Left outer join

A left outer join is a method of combining tables.
The result includes unmatched rows from only the table that is specified before the LEFT OUTER JOIN clause.

If you are joining two tables and want the result set to include unmatched rows from only one table, use a LEFT OUTER JOIN clause or a RIGHT OUTER JOIN clause.
The matching is based on the join condition.

The clause LEFT OUTER JOIN includes rows from the table that is specified before LEFT OUTER JOIN that have no matching values in the table that is specified after LEFT OUTER JOIN.

As in an inner join, the join condition can be any simple or compound search condition that does not contain a subquery reference.

Example:

The following example uses the tables in Sample data for joins.
To include rows from the PARTS table that have no matching values in the PRODUCTS table, and to include prices that exceed 10.00, run the following query:

   SELECT PART
   ,      SUPPLIER
   ,      PARTS.PROD#
   ,      PRODUCT, PRICE
   FROM   PARTS LEFT OUTER JOIN PRODUCTS
          ON PARTS.PROD#=PRODUCTS.PROD#
          AND PRODUCTS.PRICE > 10.00;

The result table looks similar to the following output:

   PART        SUPPLIER       PROD#     PRODUCT        PRICE
   =======     ============   =====     ==========     =====
   WIRE        ACWF           10        GENERATOR      45.75
   MAGNETS     BATEMAN        10        GENERATOR      45.75
   PLASTIC     PLASTIK_CORP   30        -----------  -------
   BLADES      ACE_STEEL      205       SAW            18.90
   OIL         WESTERN_CHEM   160       -----------  -------

A row from the PRODUCTS table is in the result table only if its product number matches the product number of a row in the PARTS table and the price is greater than 10.00 for that row.
Rows in which the PRICE value does not exceed 10.00 are included in the result of the join, but the PRICE value is set to null.

In this result table, the row for PROD# 30 has null values on the right two columns because the price of PROD# 30 is less than 10.00.
PROD# 160 has null values on the right two columns because PROD# 160 does not match another product number.



© Copyright IBM Corp.