Hour 13. Joining Tables in Queries


What You’ll Learn in This Hour:

An introduction to the table joins

The different types of joins

How and when joins are used

Numerous practical examples of table joins

The effects of improperly joined tables

Renaming tables in a query using an alias


To this point, all database queries you have executed have extracted data from a single table. During this hour, you learn how to join tables in a query so you can retrieve data from multiple tables.

Selecting Data from Multiple Tables

Having the capability to select data from multiple tables is one of SQL’s most powerful features. Without this capability, the entire relational database concept would not be feasible. Single-table queries are sometimes quite informative, but in the real world, the most practical queries are those whose data is acquired from multiple tables within the database.

As you witnessed in Hour 4, “The Normalization Process,” a relational database is broken into smaller, more manageable tables for simplicity and the sake of overall management ease. As tables are divided into smaller tables, the related tables are created with common columns—primary keys and foreign keys. These keys are used to join related tables to one another.

You might ask why you should normalize tables if, in the end, you are only going to rejoin the tables to retrieve the data you want. You rarely select all data from all tables, so it is better to pick and choose according to the needs of each query. Although performance might suffer slightly due to a normalized database, overall coding and maintenance are much simpler. Remember that you generally normalize the database to reduce redundancy and increase data integrity. Your overreaching task as a database administrator is to ensure the safeguarding of data.

Understanding Joins

A join combines two or more tables to retrieve data from multiple tables. Although different implementations have many ways of joining tables, you concentrate on the most common joins in this lesson. The types of joins that you learn are

• Equijoins or inner joins

• Non-equijoins

• Outer joins

• Self joins

Component of a Join Condition

As you have learned from previous hours, both the SELECT and FROM clauses are required SQL statement elements; the WHERE clause is a required element of an SQL statement when joining tables. The tables being joined are listed in the FROM clause. The join is performed in the WHERE clause. Several operators can be used to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT. However, the most common operator is the equal symbol.

Joins of Equality

Perhaps the most used and important of the joins is the equijoin, also referred to as an inner join. The equijoin joins two tables with a common column in which each is usually the primary key.

The syntax for an equijoin is

SELECT TABLE1.COLUMN1, TABLE2.COLUMN2...
FROM TABLE1, TABLE2 [, TABLE3 ]
WHERE TABLE1.COLUMN_NAME = TABLE2.COLUMN_NAME
[ AND TABLE1.COLUMN_NAME = TABLE3.COLUMN_NAME ]

Look at the following example:

SELECT EMPLOYEE_TBL.EMP_ID,
       EMPLOYEE_PAY_TBL.DATE_HIRE
FROM EMPLOYEE_TBL,

       EMPLOYEE_PAY_TBL
WHERE EMPLOYEE_TBL.EMP_ID = EMPLOYEE_PAY_TBL.EMP_ID;

This SQL statement returns the employee identification and the employee’s date of hire. The employee identification is selected from EMPLOYEE_TBL (although it exists in both tables, you must specify one table), and the hire date is selected from EMPLOYEE_PAY_TBL. Because the employee identification exists in both tables, you must justify both columns with the table name. By justifying the columns with the table names, you tell the database server where to get the data.


By the Way: Using Indentation in SQL Statements

Take note of the sample SQL statements. Indentation is used in the SQL statements to improve overall readability. Indentation is not required; however, it is recommended.


Data in the following example is selected from EMPLOYEE_TBL and EMPLOYEE_PAY_TBL because desired data resides in each of the two tables. An equijoin is used.

SELECT EMPLOYEE_TBL.EMP_ID, EMPLOYEE_TBL.LAST_NAME,
       EMPLOYEE_PAY_TBL.POSITION
FROM EMPLOYEE_TBL, EMPLOYEE_PAY_TBL
WHERE EMPLOYEE_TBL.EMP_ID = EMPLOYEE_PAY_TBL.EMP_ID;

EMP_ID    LAST_NAM POSITION
--------- -------- -------------
311549902 STEPHENS MARKETING
442346889 PLEW     TEAM LEADER
213764555 GLASS    SALES MANAGER
313782439 GLASS    SALESMAN
220984332 WALLACE  SHIPPER
443679012 SPURGEON SHIPPER

6 rows selected.

Notice that each column in the SELECT clause is preceded by the associated table name to identify each column. This is called qualifying columns in a query. Qualifying columns is only necessary for columns that exist in more than one table referenced by a query. You usually qualify all columns for consistency and to avoid questions when debugging or modifying SQL code.

Additionally, the SQL syntax provides for a more readable version of the previous syntax by introducing the JOIN syntax. The JOIN syntax is as follows:

SELECT TABLE1.COLUMN1, TABLE2.COLUMN2...
FROM TABLE1
INNER JOIN TABLE2 ON TABLE1.COLUMN_NAME = TABLE2.COLUMN_NAME

As you can see, the join operator is removed from the WHERE clause and instead replaced with the JOIN syntax. The table being joined is added after the JOIN syntax, and then the JOIN operators are placed after the ON qualifier. In the following example, the previous query for employee identification and hire date is rewritten to use the JOIN syntax:

SELECT EMPLOYEE_TBL.EMP_ID,
       EMPLOYEE_PAY_TBL.DATE_HIRE
FROM EMPLOYEE_TBL
INNER JOIN EMPLOYEE_PAY_TBL
ON EMPLOYEE_TBL.EMP_ID = EMPLOYEE_PAY_TBL.EMP_ID;

Notice that this query returns the same set of data as the previous version, even though the syntax is different. So you may use either version of the syntax without fear of coming up with different results.

Using Table Aliases

You use table aliases to rename a table in a particular SQL statement. The renaming is a temporary; the actual table name does not change in the database. As you learn later in the “Self Joins” section, giving the tables aliases is a necessity for the self join. Giving tables aliases is most often for saving keystrokes, which results in a shorter and easier-to-read SQL statement. In addition, fewer keystrokes means fewer keystroke errors. Also, programming errors are typically less frequent if you can refer to an alias, which is often shorter in length and more descriptive of the data with which you are working. Giving tables aliases also means that the columns being selected must be qualified with the table alias. The following are some examples of table aliases and the corresponding columns:

SELECT E.EMP_ID, EP.SALARY, EP.DATE_HIRE, E.LAST_NAME
FROM EMPLOYEE_TBL E,
     EMPLOYEE_PAY_TBL EP
WHERE E.EMP_ID = EP.EMP_ID
AND EP.SALARY > 20000;

The tables have been given aliases in the preceding SQL statement. EMPLOYEE_TBL has been renamed E. EMPLOYEE_PAY_TBL has been renamed EP. The choice of what to rename the tables is arbitrary. The letter E is chosen because EMPLOYEE_TBL starts with E. Because EMPLOYEE_PAY_TBL also begins with the letter E, you cannot use E again. Instead, the first letter (E) and the first letter of the second word in the name (PAY) are used as the alias. The selected columns were justified with the corresponding table alias. Note that SALARY was used in the WHERE clause and must be justified with the table alias.

Joins of Non-Equality

A non-equijoin joins two or more tables based on a specified column value not equaling a specified column value in another table. The syntax for the non-equijoin is

FROM TABLE1, TABLE2 [, TABLE3 ]
WHERE TABLE1.COLUMN_NAME != TABLE2.COLUMN_NAME
[ AND TABLE1.COLUMN_NAME != TABLE2.COLUMN_NAME ]

An example is as follows:

SELECT EMPLOYEE_TBL.EMP_ID, EMPLOYEE_PAY_TBL.DATE_HIRE
FROM EMPLOYEE_TBL,
     EMPLOYEE_PAY_TBL
WHERE EMPLOYEE_TBL.EMP_ID != EMPLOYEE_PAY_TBL.EMP_ID;

The preceding SQL statement returns the employee identification and the date of hire for all employees who do not have a corresponding record in both tables. The following example is a join of non-equality:

SELECT E.EMP_ID, E.LAST_NAME, P.POSITION
FROM EMPLOYEE_TBL E,
     EMPLOYEE_PAY_TBL P
WHERE E.EMP_ID <> P.EMP_ID;

EMP_ID    LAST_NAM POSITION
--------- -------- ------------
442346889 PLEW     MARKETING
213764555 GLASS    MARKETING
313782439 GLASS    MARKETING
220984332 WALLACE  MARKETING
443679012 SPURGEON MARKETING
311549902 STEPHENS TEAM LEADER
213764555 GLASS    TEAM LEADER
313782439 GLASS    TEAM LEADER
220984332 WALLACE  TEAM LEADER
443679012 SPURGEON TEAM LEADER
311549902 STEPHENS SALES MANAGER
442346889 PLEW     SALES MANAGER
313782439 GLASS    SALES MANAGER
220984332 WALLACE  SALES MANAGER
443679012 SPURGEON SALES MANAGER
311549902 STEPHENS SALESMAN
442346889 PLEW     SALESMAN
213764555 GLASS    SALESMAN
220984332 WALLACE  SALESMAN
443679012 SPURGEON SALESMAN
311549902 STEPHENS SHIPPER
442346889 PLEW     SHIPPER
213764555 GLASS    SHIPPER
313782439 GLASS    SHIPPER
443679012 SPURGEON SHIPPER


Watch Out!: Non-Equijoins Can Add Data

When using non-equijoins, you might receive several rows of data that are of no use to you. Check your results carefully.


You might be curious why 30 rows were retrieved when only 6 rows exist in each table. Every record in EMPLOYEE_TBL has a corresponding record in EMPLOYEE_PAY_TBL. Because non-equality was tested in the join of the two tables, each row in the first table is paired with all rows from the second table, except for its own corresponding row. This means that each of the 6 rows is paired with 5 unrelated rows in the second table; 6 rows multiplied by 5 rows equals 30 rows total.

In the earlier section’s test for equality example, each of the six rows in the first table were paired with only one row in the second table (each row’s corresponding row); six rows multiplied by one row yields a total of six rows.

Outer Joins


Watch Out!: Join Syntax Varies Widely

You must check your particular implementation for exact usage and syntax of the outer join. The (+) symbol is used by some major implementations, but it is nonstandard. In fact, this varies somewhat between versions of implementations. For example, Microsoft SQL Server 2000 supports this type of join syntax, but SQL Server 2005 and newer versions do not. Be sure to carefully consider using this syntax before implementing.


An outer join returns all rows that exist in one table, even though corresponding rows do not exist in the joined table. The (+) symbol denotes an outer join in a query. The (+) is placed at the end of the table name in the WHERE clause. The table with the (+) should be the table that does not have matching rows. In many implementations, the outer join is broken into joins called left outer join, right outer join, and full outer join. The outer join in these implementations is normally optional.

The general syntax for an outer join is

FROM TABLE1
{RIGHT | LEFT | FULL} [OUTER] JOIN
ON TABLE2


Did You Know?: Use of Outer Joins

You can use the outer join on only one side of a JOIN condition; however, you can use an outer join on more than one column of the same table in the JOIN condition.


The Oracle syntax is

FROM TABLE1, TABLE2 [, TABLE3 ]
WHERE TABLE1.COLUMN_NAME[(+)] = TABLE2.COLUMN_NAME[(+)]
[ AND TABLE1.COLUMN_NAME[(+)] = TABLE3.COLUMN_NAME[(+)]]

The concept of the outer join is explained in the next two examples. In the first example, the product description and the quantity ordered are selected; both values are extracted from two separate tables. One important factor to keep in mind is that there might not be a corresponding record in ORDERS_TBL for every product. A regular join of equality is performed:

SELECT P.PROD_DESC, O.QTY
FROM PRODUCTS_TBL P,
     ORDERS_TBL O
WHERE P.PROD_ID = O.PROD_ID;

PROD_DESC                                QTY
-----------------------------------     -----------
PLASTIC PUMPKIN 18 INCH                   2
LIGHTED LANTERNS                         10
PLASTIC SPIDERS                          30
LIGHTED LANTERNS                         20
FALSE PARAFFIN TEETH                     20
PUMPKIN CANDY                            10
FALSE PARAFFIN TEETH                     10
WITCH COSTUME                             5
CANDY CORN                               45
LIGHTED LANTERNS                         25
PLASTIC PUMPKIN 18 INCH                  25
WITCH COSTUME                            30
FALSE PARAFFIN TEETH                     15
PLASTIC SPIDERS                          50
PLASTIC PUMPKIN 18 INCH                  25
PLASTIC PUMPKIN 18 INCH                  25
WITCH COSTUME                             1

17 rows selected.

Only 17 rows were selected with only 7 products listed, but there are 9 distinct products. You want to display all products, whether they have been placed on order or not.

The next example accomplishes the desired output through the use of an outer join. Oracle’s syntax is used here:

SELECT P.PROD_DESC, O.QTY
FROM PRODUCTS_TBL P,
     ORDERS_TBL O
WHERE P.PROD_ID = O.PROD_ID(+);


PROD_DESC                                QTY
-------------------------------------  ----------
WITCH COSTUME                              5
WITCH COSTUME                             30
WITCH COSTUME                              1
ASSORTED MASKS                           NULL
FALSE PARAFFIN TEETH                      20
FALSE PARAFFIN TEETH                      10
FALSE PARAFFIN TEETH                      15
ASSORTED COSTUMES                        NULL
PLASTIC PUMPKIN 18 INCH                    2
PLASTIC PUMPKIN 18 INCH                   25
PLASTIC PUMPKIN 18 INCH                   25
PLASTIC PUMPKIN 18 INCH                   25
PUMPKIN CANDY                             10
PLASTIC SPIDERS                           30
PLASTIC SPIDERS                           50
CANDY CORN                                45
LIGHTED LANTERNS                          10
LIGHTED LANTERNS                          20
LIGHTED LANTERNS                          25

19 rows selected.

You can also use the more verbose standard join syntax discussed earlier to achieve the same result. The following code achieves the same result but uses the more verbose version of the join syntax, which makes it easier to read.

SELECT P.PROD_DESC, O.QTY
FROM PRODUCTS_TBL P
LEFT OUTER JOIN  ORDERS_TBL O
ON P.PROD_ID = O.PROD_ID;

PROD_DESC                                QTY
--------------------------------------  ----------
WITCH COSTUME                               5
WITCH COSTUME                              30
WITCH COSTUME                               1
ASSORTED MASKS                           NULL
FALSE PARAFFIN TEETH                       20
FALSE PARAFFIN TEETH                       10
FALSE PARAFFIN TEETH                       15
ASSORTED COSTUMES                        NULL
PLASTIC PUMPKIN 18 INCH                     2
PLASTIC PUMPKIN 18 INCH                    25
PLASTIC PUMPKIN 18 INCH                    25
PLASTIC PUMPKIN 18 INCH                    25
PUMPKIN CANDY                              10
PLASTIC SPIDERS                            30
PLASTIC SPIDERS                            50
CANDY CORN                                 45

LIGHTED LANTERNS                           10
LIGHTED LANTERNS                           20
LIGHTED LANTERNS                           25

19 rows selected.

All products were returned by the query, even though they might not have had a quantity ordered. The outer join is inclusive of all rows of data in PRODUCTS_TBL, whether a corresponding row exists in ORDERS_TBL or not.

Self Joins

The self join joins a table to itself, as if the table were two tables, temporarily renaming at least one table in the SQL statement using a table alias. The syntax is as follows:

SELECT A.COLUMN_NAME, B.COLUMN_NAME, [ C.COLUMN_NAME ]
FROM TABLE1 A, TABLE2 B [, TABLE3 C ]
WHERE A.COLUMN_NAME = B.COLUMN_NAME
[ AND A.COLUMN_NAME = C.COLUMN_NAME ]

The following is an example:

SELECT A.LAST_NAME, B.LAST_NAME, A.FIRST_NAME
FROM EMPLOYEE_TBL A,
     EMPLOYEE_TBL B
WHERE A.LAST_NAME = B.LAST_NAME;

The preceding SQL statement returns the employees’ first names for all the employees with the same last name from EMPLOYEE_TBL. Self joins are useful when all the data you want to retrieve resides in one table, but you must somehow compare records in the table to other records in the table.

You may also use the alternate INNER JOIN syntax as shown here to obtain the same result:

SELECT A.LAST_NAME, B.LAST_NAME, A.FIRST_NAME
FROM EMPLOYEE_TBL A
INNER JOIN EMPLOYEE_TBL B
ON A.LAST_NAME = B.LAST_NAME;

Another common example used to explain a self join follows: Suppose you have a table that stores an employee identification number, the employee’s name, and the employee identification number of the employee’s manager. You might want to produce a list of all employees and their managers’ names. The problem is that the manager name does not exist as a category in the table:

SELECT * FROM EMP;

ID   NAME      MGR_ID
---  ------    --------
1    JOHN      0
2    MARY      1
3    STEVE     1
4    JACK      2
5    SUE       2

In the following example, we have included the table EMP twice in the FROM clause of the query, giving the table two aliases for the purpose of the query. By providing two aliases, it is as if you are selecting from two distinct tables. All managers are also employees, so the JOIN condition between the two tables compares the value of the employee identification number from the first table with the manager identification number in the second table. The first table acts as a table that stores employee information, whereas the second table acts as a table that stores manager information:

SELECT E1.NAME, E2.NAME
FROM EMP E1, EMP E2
WHERE E1.MGR_ID = E2.ID;

NAME      NAME
-------   -------
MARY      JOHN
STEVE     JOHN
JACK      MARY
SUE       MARY

Joining on Multiple Keys

Most join operations involve the merging of data based on a key in one table and a key in another table. Depending on how your database has been designed, you might have to join on more than one key field to accurately depict that data in your database. You might have a table that has a primary key that is composed of more than one column. You might also have a foreign key in a table that consists of more than one column, which references the multiple column primary key.

Consider the following Oracle tables that are used here for examples only:

SQL> desc prod
Name                                      Null?    Type
----------------------------------------   -------  -----------------------------
SERIAL_NUMBER                             NOT NULL NUMBER(10)
VENDOR_NUMBER                             NOT NULL NUMBER(10)
PRODUCT_NAME                              NOT NULL VARCHAR2(30)

COST                                      NOT NULL NUMBER(8,2)

SQL> desc ord
Name                                      Null?    Type
---------------------------------------   -------  -----------------------------
ORD_NO                                    NOT NULL NUMBER(10)
PROD_NUMBER                               NOT NULL NUMBER(10)
VENDOR_NUMBER                             NOT NULL NUMBER(10)
QUANTITY                                  NOT NULL NUMBER(5)
ORD_DATE                                  NOT NULL DATE

The primary key in PROD is the combination of the columns SERIAL_NUMBER and VENDOR_NUMBER. Perhaps two products can have the same serial number within the distribution company, but each serial number is unique per vendor.

The foreign key in ORD is also the combination of the columns SERIAL_NUMBER and VENDOR_NUMBER.

When selecting data from both tables (PROD and ORD), the join operation might appear as follows:

SELECT P.PRODUCT_NAME, O.ORD_DATE, O.QUANTITY
FROM PROD P, ORD O
WHERE P.SERIAL_NUMBER = O.SERIAL_NUMBER
  AND P.VENDOR_NUMBER = O.VENDOR_NUMBER;

Similarly, if you were using the INNER JOIN syntax, you would merely list the multiple join operations after the ON keyword, as shown here:

SELECT P.PRODUCT_NAME, O.ORD_DATE, O.QUANTITY
FROM PROD P,
INNER JOIN ORD O ON P.SERIAL_NUMBER = O.SERIAL_NUMBER
  AND P.VENDOR_NUMBER = O.VENDOR_NUMBER;

Join Considerations

You should consider several things before using joins: what columns(s) to join on, whether there is no common column to join on, and what the performance issues are. More joins in a query means the database server has to do more work, which means that more time is taken to retrieve data. You cannot avoid joins when retrieving data from a normalized database, but it is imperative to ensure that joins are performed correctly from a logical standpoint. Incorrect joins can result in serious performance degradation and inaccurate query results. Performance issues are discussed in more detail in Hour 18, “Managing Database Users.”

Using a Base Table

What should you join on? Should you have the need to retrieve data from two tables that do not have a common column to join, you must join on another table that has a common column or columns to both tables. That table becomes the base table. A base table joins one or more tables that have common columns, or joins tables that do not have common columns. Use the following three tables for an example of a base table:

CUSTOMER_TBL
CUST_ID         VARCHAR(10)    NOT NULL     primary key
CUST_NAME       VARCHAR(30)    NOT NULL
CUST_ADDRESS    VARCHAR(20)    NOT NULL
CUST_CITY       VARCHAR(15)    NOT NULL
CUST_STATE      VARCHAR(2)     NOT NULL
CUST_ZIP        INTEGER(5)     NOT NULL
CUST_PHONE      INTEGER(10)
CUST_FAX        INTEGER(10)

ORDERS_TBL
ORD_NUM            VARCHAR(10)     NOT NULL    primary key
CUST_ID            VARCHAR(10)     NOT NULL
PROD_ID            VARCHAR(10)     NOT NULL
QTY                INTEGER(6)      NOT NULL
ORD_DATE           DATETIME

PRODUCTS_TBL
PROD_ID            VARCHAR(10)     NOT NULL    primary key
PROD_DESC          VARCHAR(40)     NOT NULL
COST               DECIMAL(6,2)    NOT NULL

Say you have a need to use CUSTOMERS_TBL and PRODUCTS_TBL. There is no common column in which to join the tables. Now look at ORDERS_TBL. ORDERS_TBL has a CUST_ID column to join with CUSTOMERS_TBL, which also has a CUST_ID column. PRODUCTS_TBL has a PROD_ID column, which is also in ORDERS_TBL. The JOIN conditions and results look like the following:

SELECT C.CUST_NAME, P.PROD_DESC
FROM CUSTOMER_TBL C,
     PRODUCTS_TBL P,
     ORDERS_TBL O
WHERE C.CUST_ID = O.CUST_ID
  AND P.PROD_ID = O.PROD_ID;

CUST_NAME                      PROD_DESC
------------------------------ -----------------------
LESLIE GLEASON                 WITCH COSTUME
SCHYLERS NOVELTIES             PLASTIC PUMPKIN 18 INCH
WENDY WOLF                     PLASTIC PUMPKIN 18 INCH
GAVINS PLACE                   LIGHTED LANTERNS

SCOTTYS MARKET                 FALSE PARAFFIN TEETH
ANDYS CANDIES                  KEY CHAIN

6 rows selected.


By the Way: Using Aliases on Tables and Columns

Note the use of table aliases and their use on the columns in the WHERE clause.


The Cartesian Product

The Cartesian product is a result of a Cartesian join or “no join.” If you select from two or more tables and do not join the tables, your output is all possible rows from all the tables selected. If your tables were large, the result could be hundreds of thousands, or even millions, of rows of data. A WHERE clause is highly recommended for SQL statements retrieving data from two or more tables. The Cartesian product is also known as a cross join.

The syntax is

FROM TABLE1, TABLE2 [, TABLE3 ]
WHERE TABLE1, TABLE2 [, TABLE3 ]

The following is an example of a cross join, or the dreaded Cartesian product:

SELECT E.EMP_ID, E.LAST_NAME, P.POSITION
FROM EMPLOYEE_TBL E,
     EMPLOYEE_PAY_TBL P;

EMP_ID    LAST_NAM POSITION
--------- -------- --------------
311549902 STEPHENS MARKETING
442346889 PLEW     MARKETING
213764555 GLASS    MARKETING
313782439 GLASS    MARKETING
220984332 WALLACE  MARKETING
443679012 SPURGEON MARKETING
311549902 STEPHENS TEAM LEADER
442346889 PLEW     TEAM LEADER
213764555 GLASS    TEAM LEADER
313782439 GLASS    TEAM LEADER
220984332 WALLACE  TEAM LEADER
443679012 SPURGEON TEAM LEADER
311549902 STEPHENS SALES MANAGER
442346889 PLEW     SALES MANAGER
213764555 GLASS    SALES MANAGER
313782439 GLASS    SALES MANAGER
220984332 WALLACE  SALES MANAGER

443679012 SPURGEON SALES MANAGER
311549902 STEPHENS SALESMAN
442346889 PLEW     SALESMAN
213764555 GLASS    SALESMAN
313782439 GLASS    SALESMAN
220984332 WALLACE  SALESMAN
443679012 SPURGEON SALESMAN
311549902 STEPHENS SHIPPER
442346889 PLEW     SHIPPER
213764555 GLASS    SHIPPER
313782439 GLASS    SHIPPER
220984332 WALLACE  SHIPPER
443679012 SPURGEON SHIPPER
311549902 STEPHENS SHIPPER
442346889 PLEW     SHIPPER
213764555 GLASS    SHIPPER
313782439 GLASS    SHIPPER
220984332 WALLACE  SHIPPER
443679012 SPURGEON SHIPPER

36 rows selected.

Data is being selected from two separate tables, yet no JOIN operation is performed. Because you have not specified how to join rows in the first table with rows in the second table, the database server pairs every row in the first table with every row in the second table. Because each table has 6 rows of data each, the product of 36 rows selected is achieved from 6 rows multiplied by 6 rows.

To fully understand exactly how the Cartesian product is derived, study the following example:

SQL> SELECT X FROM TABLE1;

X
-
A
B
C
D

4 rows selected.

SQL> SELECT V FROM TABLE2;

X
-
A
B
C
D


4 rows selected.

SQL> SELECT TABLE1.X, TABLE2.X
  2* FROM TABLE1, TABLE2;

X X
- -
A A
B A
C A
D A
A B
B B
C B
D B
A C
B C
C C
D C
A D
B D
C D
D D

16 rows selected.


Watch Out!: Ensure That All Tables Are Joined

Be careful to join all tables in a query. If two tables in a query have not been joined and each table contains 1,000 rows of data, the Cartesian product consists of 1,000 rows multiplied by 1,000 rows, which results in a total of 1,000,000 rows of data returned. Cartesian products, when dealing with large amounts of data, can cause the host computer to stall or crash in some cases, based on resource usage on the host computer. Therefore, it is important for the database administrator (DBA) and system administrator to closely monitor for long-running queries.


Summary

You have been introduced to one of the most robust features of SQL—the table join. Imagine the limits if you were not able to extract data from more than one table in a single query. You were shown several types of joins, each serving its own purpose depending on conditions placed on the query. Joins are used to link data from tables based on equality and non-equality. Outer joins are powerful, allowing data to be retrieved from one table, even though associated data is not found in a joined table. Self joins are used to join a table to itself. Beware of the cross join, more commonly known as the Cartesian product. The Cartesian product is the resultset of a multiple table query without a join, often yielding a large amount of unwanted output. When selecting data from more than one table, be sure to properly join the tables according to the related columns (normally primary keys). Failure to properly join tables could result in incomplete or inaccurate output.

Q&A

Q. When joining tables, must they be joined in the same order that they appear in the FROM clause?

A. No, they do not have to appear in the same order; however, performance might benefit depending on the order of tables in the FROM clause and the order in which tables are joined.

Q. When using a base table to join unrelated tables, must I select any columns from the base table?

A. No, the use of a base table to join unrelated tables does not mandate that columns from the base table be selected.

Q. Can I join on more than one column between tables?

A. Yes, some queries might require you to join on more than one column per table to provide a complete relationship between rows of data in the joined tables.

Workshop

The following workshop is composed of a series of quiz questions and practical exercises. The quiz questions are designed to test your overall understanding of the current material. The practical exercises are intended to afford you the opportunity to apply the concepts discussed during the current hour, as well as build upon the knowledge acquired in previous hours of study. Please take time to complete the quiz questions and exercises before continuing. Refer to Appendix C, “Answers to Quizzes and Exercises,” for answers.

Quiz

1. What type of join would you use to return records from one table, regardless of the existence of associated records in the related table?

2. The join conditions are located in which parts of the SQL statement?

3. What type of join do you use to evaluate equality among rows of related tables?

4. What happens if you select from two different tables but fail to join the tables?

5. Use the following tables:

ORDERS_TBL
ORD_NUM      VARCHAR(10)      NOT NULL     primary key
CUST_ID      VARCHAR(10)      NOT NULL
PROD_ID      VARCHAR(10)      NOT NULL
QTY          Integer(6)       NOT NULL
ORD_DATE     DATETIME

PRODUCTS_TBL
PROD_ID      VARCHAR(10)      NOT NULL     primary key
PROD_DESC    VARCHAR(40)      NOT NULL
COST         DECIMAL(,2)      NOT NULL

Is the following syntax correct for using an outer join?

SELECT C.CUST_ID, C.CUST_NAME, O.ORD_NUM
FROM CUSTOMER_TBL C, ORDERS_TBL O
WHERE C.CUST_ID(+) = O.CUST_ID(+)

What would the query look like if you used the verbose JOIN syntax?

Exercises

1. Type the following code into the database and study the resultset (Cartesian product):

SELECT E.LAST_NAME, E.FIRST_NAME, EP.DATE_HIRE
FROM EMPLOYEE_TBL E,
     EMPLOYEE_PAY_TBL EP;

2. Type the following code to properly join EMPLOYEE_TBL and EMPLOYEE_PAY_TBL:

SELECT E.LAST_NAME, E.FIRST_NAME, EP.DATE_HIRE
FROM EMPLOYEE_TBL E,
     EMPLOYEE_PAY_TBL EP
WHERE E.EMP_ID = EP.EMP_ID;

3. Rewrite the SQL query from Exercise 2, using the INNER JOIN syntax.

4. Write an SQL statement to return the EMP_ID, LAST_NAME, and FIRST_NAME columns from EMPLOYEE_TBL and SALARY and BONUS columns from EMPLOYEE_PAY_TBL. Use both types of INNER JOIN techniques. Once that’s completed, use the queries to determine what the average employee salary per city is.

5. Write a few queries with join operations on your own.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.54.242