SQL Joins   «Prev  Next»

Create Simple Join [SQL] - Exercise Result

You entered:

How are the two tables related?

These two tables are related based on the customer ID, so you will use that as the linking column. Using this information, the SELECT statement becomes

SELECT * FROM Customer, Orders 
WHERE orders.cust_id=customer.cust_id 

The result is that one row is returned for every match between the two tables.

Multitable Queries using Joins

Most useful queries request data from two or more tables in a database. For example, these requests for data in the sample database draw data from two, three, and four tables respectively:
  1. List the salespeople and the offices where they work (SALESREPS and OFFICES tables).
  2. List each order placed last week, showing the order amount, the name of the customer who placed it, and the name of the product ordered (ORDERS, CUSTOMERS, and PRODUCTS tables).
  3. Show all orders taken by salespeople in the Eastern region, showing the product description and salesperson (ORDERS, SALESREPS, OFFICES, and PRODUCTS tables).


Join Data from Two or more Tables

SQL allows you to retrieve data that answers these requests through multitable queries that join data from two or more tables. These queries and the SQL join facility are described in this chapter. We begin with the join capabilities that have been a part of SQL from the earliest days and are found in all SQL products today. The later sections describe additional join capabilities that first appeared in SQL2 standard and are found in most mainstream products.

Two-Table Query Example

The best way to understand the facilities that SQL provides for multitable queries is to start with a simple request that combines data from two different tables:
List all orders, showing the order number and amount, and the name and credit limit of the customer who placed it.
The four specific data items requested are clearly stored in two different tables, as shown in Figure 7-4 below.
  1. The ORDERS table contains the order number and amount of each order, but does not have customer names or credit limits.
  2. The CUSTOMERS table contains the customer names and credit limits, but it lacks any information about orders.

A request that spans 2 tables
Figure 7-4: A request that spans 2 tables