Practical SQL: Three Ways to JOIN

SQL
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

JOINing tables is one of the fundamental tasks in SQL, and this article explains three basic syntactical approaches.

 

SQL is the tool of choice for querying relational data, and the whole idea behind relational data is that the tables are related. What this means is that a common field in two tables can be used to tie rows from each table together into a coherent set of data. In SQL, this is performed via the JOIN, which has three distinct syntactical variations. This article will explain the differences, including a recent change that might catch you unaware.

Defining the Table

No sense in wasting any time. Let's go straight to the file definitions. For this exercise, I'm using two files: ORDERS and ORDERLINES. ORDERS holds the order headers while ORDERLINES contains the lines for those orders. Below you'll see the fields for each of the files.

 

 Seq. Base PF    Field Name Field Description         Key Tp  Pos  Len Dec

  1.0 ORDERS     CUSTOMER                                 S     1     6  0

  2.0            ORDERNO                                  S     7     6  0

  3.0            SHIPTO                                   S    13     4  0

  4.0            ENTERED                                  L    17    10  0

  5.0            STATUS                                   A    27     1   

 

  1.0 ORDERLINES ORDERNO                                  S     1     6  0

  2.0            ITEM                                     A     7    15   

  3.0            QUANTITY                                 S    22    11  3

  4.0            PRICE                                    S    33     9  4

  5.0            SHIPPED                                  S    42    11  3

  6.0            STATUS                                   A    53     1   

 

You might recognize the layout of the field definitions; these are screen captures from the wonderful WRKDBF utility. WRKDBF was originally freeware and is now a for-fee program available from the author for the very reasonable price of $449 (compared to a DBU license, which has more functionality for a somewhat higher price).

 

If you want to follow along, use the tool of your choice to create a couple of tables and add some data. I added a few records for a single order, and now it's time to access them.

The Traditional Method

Back in the early days of JOINs, all you did was specify multiple files in your query and then use a WHERE clause to limit the data to only those records that matched your JOIN criteria. In my case, I want to tie together records that have the same order number. The syntax is straightforward:

 

select * from ORDERS, ORDERLINES

where ORDERS.ORDERNO = ORDERLINES.ORDERNO

  and ORDERS.ORDERNO = 123456

 

All I do is define the two files in the SELECT keyword. Note that I am using my preferred case conventions in the example SQL statements: all SQL keywords are in lowercase, and all external table and column names are in uppercase. It really makes the external names stand out for me, but it's a little inconsistent with writing an article because in the article I usually type the SQL keywords in uppercase along with the table and column names.

 

I define the JOIN in the WHERE clause: ORDERS.ORDERNO = ORDERLINES.ORDERNO. Because the column name exists in two files, it's considered ambiguous and I must qualify it with the file name. This is a negative for those folks who like to use the same field name in different files.

 

Anyway, I get a nice result from this:

 

CUSTOMER   ORDERNO   SHIPTO   ENTERED   STATUS  ORDERNO   ITEM               QUANTITY

  10,010   123,456        1   09/18/11    A     123,456   ABC1234              20.000

  10,010   123,456        1   09/18/11    A     123,456   998-SD2             122.340

 

I'm showing only the first eight columns: it shows order header information in the first five columns and order detail in the last three; the remaining order detail columns are not shown. The order header information is repeated because both lines belong to the same order. Also, the ORDERNO field shows up twice, once as part of the ORDERS columns and once as part of the ORDERLINES columns. This will be important later.

 

Note that I limited the query to a single order by specifying the order number in the WHERE clause. This is one of the problems with this syntax; the WHERE clause includes both the JOIN specification and any additional row selection criteria. This changes when we move to the JOIN … ON syntax.

JOIN … ON

The next incarnation of the JOIN syntax introduces the JOIN keyword. This brings us not only the JOIN (also known as the INNER JOIN), but also the LEFT and RIGHT OUTER JOINs, the FULL OUTER JOIN, the CROSS JOIN, and the EXCEPTION JOIN. This article doesn't address the differences between those various JOIN types, but they are very important to business applications. You can read more about the various types of JOINs by following the hyperlinks for each one or by starting at the IBM Infocenter page on the topic.

 

For this article, though, let's just use the standard INNER JOIN and see how it changes the syntax.

 

select * from ORDERS join ORDERLINES

  on ORDERS.ORDERNO = ORDERLINES.ORDERNO

  where ORDERS.ORDERNO = 123456

 

The changes are negligible, as you can see. All I have to do is add a new ON clause and move the JOIN criteria from the WHERE clause to the ON clause. The WHERE clause now only contains actual row selection conditions and thus we've segregated the JOIN and WHERE terms. This makes the code more readable to me, and the result is the same:

 

CUSTOMER   ORDERNO   SHIPTO   ENTERED   STATUS  ORDERNO   ITEM               QUANTITY

  10,010   123,456        1   09/18/11    A     123,456   ABC1234              20.000

  10,010   123,456        1   09/18/11    A     123,456   998-SD2             122.340

 

One thing to note: the column names for the JOIN don't have to be the same. If the column names for the order number were different for the two tables, we could still use this syntax, and in fact it would be a little less typing. Let's say the fields were OHORDER and OLORDER (OH for order header and OL for order line). The ON clause would simplify down to this:

 

  on OHORDER = OLORDER

 

When the column names are different, I don't need to qualify them, so I don't need to type the table names. But if the column names are different, I can't show you the third variation, the USING clause.

USING

The last alternative of the JOIN syntax still uses the JOIN keyword, but instead of the ON clause, we see a USING clause.

 

select * from ORDERS join ORDERLINES

  using (ORDERNO)

  where ORDERS.ORDERNO = 123456

 

You'll note a lot less typing in this case. Basically, you specify the field or fields used in the JOIN in a parenthetical comma-separated list (the parentheses are required). Clearly, this works only when the field names are the same, but when they are, you get the same results:

 

CUSTOMER   ORDERNO   SHIPTO   ENTERED   STATUS  ORDERNO   ITEM               QUANTITY

  10,010   123,456        1   09/18/11    A     123,456   ABC1234              20.000

  10,010   123,456        1   09/18/11    A     123,456   998-SD2             122.340

 

Well, you did, anyway. Right up until V7.1. Now you get a slightly different result:

 

ORDERNO   CUSTOMER   SHIPTO   ENTERED   STATUS  ITEM             QUANTITY         PRICE

123,456     10,010        1   09/18/11    A     ABC1234            20.000        1.1100

123,456     10,010        1   09/18/11    A     998-SD2           122.340         .0112

 

Look closely and you'll see that the ORDERNO column is no longer repeated. In fact, it moved to the first column. Why? Well, that's because the USING syntax treats the JOIN fields a little differently. The JOIN fields are considered separate from either table and are included at the beginning of the query. If there were multiple fields in the USING clause, they'd all show up at the front of the line. And I mean it when I say that the fields are not considered part of either table. Try this:

 

select ORDERS.ORDERNO from ORDERS join ORDERLINES

using (ORDERNO)                         

        

Column ORDERNO not in table ORDERS in MCP.

 

Believe me, this caused me some real consternation the first time I ran into it. Once you've included the field in the USING clause, it is no longer considered to be a column in either table and you get an error message that frankly isn't correct. Don't be surprised. You didn't somehow magically remove a column from your table; it's just one of those little syntactical gotchas. I'd really prefer a message that said "qualified references to JOIN fields not allowed," but I understand the tendency to reuse messages that are close to the correct meaning. I don't agree, but I understand it.

Which to Use?

The older syntax using the WHERE clause should be considered obsolete. It's potentially confusing, and it has much less functionality than the JOIN clause. Get to know the JOIN—and especially the different JOIN types—and you'll have a lot more power available to you in your SQL development. In particular, OUTER JOINs are indispensable in reports, but that's another topic for another day.

 

The USING syntax can be used only when the column names match. Because of this, unless yours is a database in which the customer number has the same name in every table, you will probably have much less opportunity to take advantage of the USING clause. But in those cases where it is available, it can really reduce the amount of typing and can even avoid some typos. Just remember that if you do take advantage of USING and you have moved into the brave new world of 7.1, there are some differences. Go forth and JOIN!

as/400, os/400, iseries, system i, i5/os, ibm i, power systems, 6.1, 7.1, V7, V6R1

BLOG COMMENTS POWERED BY DISQUS