23
Mon, Dec
2 New Articles

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

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: