Mon, Apr
1 New Articles

The Hidden Power of Query, Part 1

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

IBM Query for AS/400 (a.k.a. Query/400 or Query) is the Clark Kent of the AS/400 world. On the surface, it’s a mild-mannered report writer that performs light-duty tasks with little fanfare. Its flexibility and usefulness are generally considered limited. Because Query doesn’t include built-in functions to translate a field into something else or allow users to set conditions and report in different ways based on the data, many companies look to more robust report writers to take on these challenging tasks.

But there’s a lot more to this tool than many people realize. Behind the humble façade is a powerful data formatter. The basic mathematical and character substring options available in Query can be combined like building blocks to perform much more complex logic.

Do you need to extract and reorganize numbers and character strings? Do you have to print text in only certain conditions? Those look like jobs for...Query!

Integer Division

One simple Query building block is integer division. Say you have an integer field that contains 18. If you define a result field with zero decimal places and set it to the integer field divided by 10, your new field is 2 (because Query will round 1.8 up to 2 by default). However, under integer division, the result is truncated, not rounded, yielding a value of 1 instead. In other words, the result field will always be the “tens” digit.

Integer division is made possible by setting Use Rounding to N in the Specify Processing Options panel.

This ability to extract numbers without having to change data type to character is very useful. You can change the positions of the numbers but still be able to perform arithmetic functions on the result. Take an integer date, for instance 19991231. Define a zero-decimal field called TEMP1 that will hold the date divided by 10,000. This gives you
1999. Divide this by 100 with another field called TEMP2, which will then contain 19. The two-digit year can then be extrapo-lated with a defined field that takes (TEMP1 - TEMP2 *
100). You’ve pulled out the 99, but kept it as an integer, so you can use it for other duration calculations.

In addition to parsing numeric data, the numbers can be concatenated together in different order while still maintaining their data type. For instance, if you want the integer

date 19991231 to appear as the number 123199, just apply the same logic on a slightly larger scale, as seen in Figure 1.

String Manipulation

If maintaining numeric data type is not an issue, an easy way to extract and reformat information is to use the SUBSTR and Concatenate (||) functions. SUBSTR(field, starting position, length) extracts characters, so if PARTNO = “12-456A,” SUBSTR(PARTNO,7,1) will be “A.” Concatenate attaches character strings together, so a field called REV can be defined as “REVISION “ || SUBSTR(PARTNO,7,1), which will become the string “REVISION A.”

However, SUBSTR parameters don’t have to be static fields, and type conversion can be embedded in the SUBSTR function. Using the integer DATFLD of 19991231 from the previous example, SUBSTR(DIGITS(DATFLD),5,2) produces the string “12.”

The starting position index can be dynamic as well, so if a field called DAYNUM is set to 7, SUBSTR(DIGITS(DATFLD),DAYNUM,2) produces the string “31.”

DAYNUM could also be a mathematical equation or anything else that results in a positive integer. This feature turns out to be another simple building block with hidden potential.

Data Translation

In many customized reports, the information that’s retrieved directly from the database is not in a form that the user can easily understand. If there were a way to decipher the raw data into more detailed messages, the report could be more user-friendly. Using the tools I’ve covered this far, Query can handle this type of data translation.

A character-type result field can act as a conversion table, and the integer division and SUBSTR functions can be used to extract elements from this table. Figure 2 (page
109) demonstrates how to print the word EVEN or ODD based on any given number. Integer division is applied to get the low-order digit, which is used to calculate a starting position in a conversion string. By padding each table entry with trailing blanks so there is a consistent element size, SUBSTR can print a status of the original number.

Data field translation has many other uses on reports. Dates become more meaningful as a 2 becomes FEBRUARY or a 7 becomes SATURDAY. Cryptic database codes spring to life as an error 12 is decoded into NO STOCKROOM ASSIGNED or a status code 4 now prints as NOT YET INVOICED. Higher-order digits can be translated in a way similar to the example in Figure 2, so it becomes possible to print 25 as TWENTY- FIVE.

You can even set the index to be based on the current time to print a different message each time your report is run.


Though powerful, I’m not sure how often this particular use will come in handy. Although, when concatenated with data from other defined tables that are indexed using the current microsecond, Query becomes an amusing random rumor generator!

SUBSTR’s length parameter can be a dynamic variable as well, so users can retrieve different size elements from the same table. It takes a few extra defined fields to tell Query about the starting position and length of each table element, but when this is done, reports have a much more natural look. For instance, go back to the suggestion of printing the month name based on a given date. Using 10-character fixed-length elements in your table means that 9/30 would print as “September 30,” but 5/30 would print as “May 30.” The extra seven spaces padding the end of May can be cleaned up using a method outlined in Figure 3.

Start with a table that lists all the month names back-to-back. Include a second table that lists the 2-digit starting position of each month name in the first table (JANUARY starts in table position 1, FEBRUARY starts in position 8, etc.), and a third table to define the length of each month name (JANUARY is 7 characters long, FEBRUARY is 8, etc.) The month is extracted from a data field using integer division. This number can then be used as an index to look up information across the multiple tables.

The starting position and length values are extracted from the tables in character form. One method of converting them to integer so they can be used by SUBSTR to index the main table is to use the MICROSECOND function. Appending any numeric character to the end of a time stamp string and then extracting the integer with MICROSECOND is a neat little trick that comes in handy in all kinds of situations.

In the Figure 3 example using 1000530 as an input date, the month (5) is used to extract a starting position (26) and string length (3). Once these parameters are set, a single call to SUBSTR(TABLE,26,3) will pull out the characters “MAY” without trailing blanks.

When creating a table of text that exceeds the space provided in the Define Result Field, simply break the table into multiple result fields and concatenate them all together into one final table using the || function. Query/400 allows a Result Field to be up to 32,766 characters long.

Conditional Logic

One of the most common reasons for dismissing Query as limited is the fact that no conditional logic is available. There’s no If-Then-Else function to let the report choose what data to print or to print only in certain cases. Again, using the simple techniques I described, users can set a Boolean indicator by generating a 1 or 0 based on a numeric field. This indicator can then be multiplied by other fields to effectively turn them on (NUM * 1 = NUM) or off (NUM * 0 = 0).

The DIGITS() function is a good example. When given a number, DIGITS converts the number to character. When given a negative number, it converts it to character, but the sign is dropped. This is usually an important tidbit of information that should be kept with the original number. Get it back by setting a Boolean indicator.

Figure 4 shows how to break down a number into 1 if it’s a negative number, or 0 if it’s positive.

The formula is (X - 0.001)^2 / (X^2 + 0.00001). By subtracting a small amount from the numerator before squaring, the result is just over 1.0 if the original number is negative. Otherwise the result is just under 1.0. Adding 0.00001 to the denominator makes sure that there’s never a divide-by-zero error condition. By placing the result in a zero- decimal field and suppressing the rounding function, the on/off switch is set.

With this integer variable called RESULT that tells you if your number is positive or negative, SUBSTR can use it as an index. Define a 2-character result field called SIGN, set to “ -” (blank, dash). Then when you convert any number to character, use the following to append either a blank or a negative sign onto your converted number.


This example sets the Boolean indicator by comparing a single number to zero, but you can really use any two numbers. Take the difference between two numbers, DIFF = A - B. If you run DIFF through the formula, the RESULT will be 0 if A is greater than B or 1 if A is less than or equal to B. The value can be used to calculate a dynamic SUBSTR index or as a multiplication factor to manipulate other numeric fields. Now your report can produce different output depending on the comparison of the original numbers. For an example, see “Query/400 Finds the Larger of Two Numbers” in September 2000

You thought Query wasn’t that super!

Scratching the Surface

This is just an introduction to see through to the hidden power and flexibility of Query.

Query can do a lot more with just the basic set of available functions. Calculating duration using numeric dates (so 991201 - 991130 equals 1 day and not the mathematical value of 71) and using file join and output reporting options to recursively search a tree- structure were once thought to be beyond the scope of the software. These and other building block techniques will be explored in future articles. With enough building blocks, you can make a tall building—and Query can leap it in a single bound.

If your integer date field "DATFLD" contains 19991231:

Define Field Size Decimals Definition Value

CYM 6 0 DATFLD / 100 199912 CYM00 8 0 CYM * 100 19991200 DD 2 0 DATFLD - CYM00 31
CY 4 0 CYM / 100 1999
MM 2 0 CYM - (CY * 100) 12
C 2 0 CY / 100 19
YY 2 0 CY - (C * 100) 99 NEWDATE 7 0 (MM * 10000) 123199

+ (DD * 100) + YY

Field Expression Len Dec

TEXT ‘EVENODD EVENODD EVENODD EVENODD EVENODD’ TEMP1 input / 10 4 0 INDEX input - (temp * 10) 1 0 TEMP2 ubstr(text,index*4+1,4)

Result: 12345 translates to the string “ODD“

Figure 1: Numeric data can be reformatted without changing the data type.

Figure 2: You can define a text field as a table and substring individual elements.

GIVEN THE INTEGER DATE 1000530: Field Expression Len Dec Description TABLE 'JANUARYFEBRUARYMARCHAPRILMAYJUNE Data elements of various size


POSITION '010816212629333743525967' Starting position of each element SIZE '785534469788' Character length of each element CYYMM DATFLD / 100 5 0 Date variable (Ex: 10005)

CYY DATFLD / 10000 3 0 Date variable (Ex: 100) MONTH CYYMM - (CYY * 100) 2 0 Date variable (Ex: 5) YEAR 1900 + CYY 4 0 Date variable (Ex: 2000) START_CHAR SUBSTR(POSITION,MONTH*2-1,2) Start position of Month (Ex: 26) LEN_CHAR SUBSTR(SIZE,MONTH,1) Character length of Month (Ex: '3') START MICROSECOND(TIMESTAMP('2000-01-01 Convert Character to Number

-'||START_CHAR)) LENGTH MICROSECOND(TIMESTAMP('2000-01-01 Convert Character to Number

-'||LEN_CHAR)) LABEL SUBSTR(TABLE,START,LENGTH)||' '|| Produce "MAY 30, 2000" from

SUBSTR(DIGITS(DATFLD),6,2)||', ' the number 1000530 ||DIGITS(YEAR) (NUMBER - 0.001)^2

(NUMBER^2) + 0.00001

When NUMBER < 0, RESULT = 1 When NUMBER >= 0, RESULT = 0

Field Len Dec Expression

NUMER 15 5 (NUMBER - 0.001) * (NUMBER - 0.001) DENOM 15 5 (NUMBER * NUMBER) + 0.00001 RESULT 1 0 NUMER / DENOM

Figure 3: Text strings of different sizes can be handled by varying SUBSTR’s length parameter.

Figure 4: This equation can be used to change any number to a 1 or 0 for use as a conditional indicator.



Support MC Press Online

$0.00 Raised:

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: