18
Thu, Jul
2 New Articles

Practical SQL: Variables in SQL

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

One problem with complex queries is keeping all the pieces in sync; this technique helps you do just that.

 

I've long extolled the virtues of common table expressions (or CTEs), and I've also showed you how to use UNION statements to great advantage. They're powerful, and I find them particularly well suited to performing ad hoc analysis on production data. Unfortunately, both of those techniques can fall prey to a very specific problem that has caused me severe headaches in my analyses. This article explains the problem and the recently added feature that provides a solution.

The Problem with Componentization

Let me explain the issue. Let's take a simple case, the wonderful UNION. Let's say I want to use UNION to identify all the demand for a specific item, reflecting customer orders and production material requirements (this may, for example, be a subassembly that is used in production but thatt we also sell). I'm not going to spend a lot of time laying out the files themselves; I think I can come up with suitably self-documenting file and field names. Here's what such a query might look like:

 

select MRPROD prod, MRQTY qty, MRDATE needed from PRDMATREQ

union all

select ODPROD, (ODORDERED – ODSHIPPED), ODREQDATE from CUSORDDTL

order by 1, 2

 

This is a pretty simple example. I need to then take that to the next level. I want to aggregate that value over the next two weeks. That is, I want the total for each item for the next two weeks. Not a particularly difficult extension. Let's see how that works.

 

with demand as

(select MRPROD prod, MRQTY qty, MRDATE needed from PRDMATREQ

   union all

   select ODPROD prod, (ODORDERED – ODSHIPPED) qty,

   ODREQDATE needed from CUSORDDTL)

select prod, sum(qty) from demand

where needed < current_date + 14 days

group by prod

 

You can see that the statement got a bit more complex. That's because I had to make sure the column names matched on both of the subselects in the UNION. But once I did that, I was able to start running aggregation, in this case performing a simple sum by product. I also tossed in a little date selection magic; I used the current date (available from the standard register value CURRENT_DATE) and added 14 days. I can change my date range quite easily, even setting up a range. Let's say, for example, that I want the product aggregation for the last 45 days. I replace the WHERE clause:

 

where needed between current_date – 45 days and current_date

 

Now I'm getting the total for the last 45 days. But why am I doing this? Because I want to compare my actual demand to my forecasts. Ah! So let's now calculate those:

 

with demand as

(select MRPROD prod, MRQTY qty, MRDATE needed from PRDMATREQ

   union all

   select ODPROD prod, (ODORDERED – ODSHIPPED) qty,

   ODREQDATE needed from CUSORDDTL),

demandtotals as

(select prod, sum(qty) totdemand from demand

   where needed between current_date – 45 days and current_date

   group by prod),

forecasttotals as

(select foprod, sum(foqty) totforecast from forecasts

   where fodate between current_date – 45 days and current_date

   group by foprod)

select foprod, totforecast, totdemand from

forecasttotals join demandtotals on prod = foprod

where totdemand > totforecast * 1.20

 

That's a serious piece of work right there! First, I took the aggregation of the demand totals and turned that into a second CTE called, not surprisingly, demandtotals. Next, I aggregated the forecast over the same period into a CTE called forecasttotals. Now I have my two pieces that I can compare using a simple JOIN and a formula that shows only those items where the demand exceeds the forecast by 20% or more. That's just an example; obviously, the comparison criteria could get much more complex. But up until now, I really haven't expressed a problem. But one exists, nonetheless. Let's say that after looking at these numbers, we decide we want to change the window; for example, we want to expand to 60 days rather than just 45. That's pretty easy; I can just find the two places where I have 45 days and change that to 60 days. But imagine if I only change one of them. That could be a disaster; the query would run, but the results would be out of whack, and depending on how egregious the mistake, you might not even notice until after using the numbers. Not good!

Variables to the Rescue!

And that's where the power of variables comes into play! DB2 allows you to create a variable that can then be used throughout your session. In this example, I can create a variable called "fence," which I can then use in the rest of my SQL to calculate my cutoff date. The creation of the variable is very simple:

 

create variable mylib/fence numeric (4)

 

This creates a variable named FENCE in library MYLIB. The variable is a numeric variable with four digits and an implied zero decimals. This variable is now available to any session. To use it in my example, I first set it:

 

set variable fence = 45

 

And once that's done, I can use it in my complex examples above. Here's the modified version of one of the affected lines:

 

where needed between current_date – fence days and current_date

 

As you can see, the variable is easily inserted into the statement. If I replace both hardcoded values with the variable, then all I have to do to change how the statement works is to change the variable with another SET statement. I find this technique to have a lot of value, especially in some of my more complex SQL queries. I often have to join huge files together with complex calculations, displaying only a small selection of the data. By performing the filtering first, I can often significantly reduce the time that the query takes. But if I have selection criteria in multiple places in my query, I'm vulnerable to the problem I've described of missing one of the required changes. So using a variable in the selection process removes a potential nightmare.

 

Variables aren't perfect. One of the more annoying issues is that they aren't like data areas because they don't keep their value between sessions. There are pros and cons to the idea; the reason I've heard for this design is so that different sessions can run with different values. I guess that makes sense, but it does mean that I have to remember to set my variable each time before I run the query, even if I'm setting it to the same value I used the last time I ran the session. But knowing that behavior ahead of time, I can use the feature where it is best suited.

 

So hopefully you got a little taste of some complex real-world queries as well as knowledge of a new tool to add to your SQL toolbelt. Stay tuned for more SQL know-how in upcoming articles!

Joe Pluta

Joe Pluta is the founder and chief architect of Pluta Brothers Design, Inc. He has been extending the IBM midrange since the days of the IBM System/3. Joe uses WebSphere extensively, especially as the base for PSC/400, the only product that can move your legacy systems to the Web using simple green-screen commands. He has written several books, including Developing Web 2.0 Applications with EGL for IBM i, E-Deployment: The Fastest Path to the Web, Eclipse: Step by Step, and WDSC: Step by Step. Joe performs onsite mentoring and speaks at user groups around the country. You can reach him at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Joe Pluta available now on the MC Press Bookstore.

Developing Web 2.0 Applications with EGL for IBM i Developing Web 2.0 Applications with EGL for IBM i
Joe Pluta introduces you to EGL Rich UI and IBM’s Rational Developer for the IBM i platform.
List Price $39.95

Now On Sale

WDSC: Step by Step WDSC: Step by Step
Discover incredibly powerful WDSC with this easy-to-understand yet thorough introduction.
List Price $74.95

Now On Sale

Eclipse: Step by Step Eclipse: Step by Step
Quickly get up to speed and productivity using Eclipse.
List Price $59.00

Now On Sale

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: