• The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
Menu
  • The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
  • Guru: Conditional SQL Unions

    July 17, 2017 Ted Holt

    SQL unions combine two or more result sets into one. That’s what they were designed to do. But unions also provide a way to choose between alternate result sets, i.e. to enable or disable SELECT statements at run time. I have used this feature to advantage on numerous occasions. Here’s how it’s done.

    First consider the nature of unions. Each result set of a union can return data or no data, depending on the criteria in the WHERE and HAVING clauses. If a SELECT retrieves no data, the system appends an empty set to the union result. The way to turn a SELECT on or off, then, is to control the selection criteria in the WHERE and HAVING clauses.

    As always, we need an example. Let’s start with a simple query. Let’s make a list of customers in Minnesota and New York. This would be a very easy query.

    select State, City, CusNum, LstNam
      from qiws.qcustcdt
     where State in ('MN', 'NY')
    

    If we have customers in either or both of those states, we get a result set.

    State City CusNum LstNam
    MN Isle 846283 Alison
    MN Isle 583990 Abraham
    NY Clay 839283 Jones
    NY Hector 397267 Tyron
    NY Hector 192837 Lee

    If we have no customers in those states, then no rows (records) match the WHERE clause and we get an empty set.

    Suppose that the result set, whether empty or populated, loads a grid in a GUI form. If the result set contains data, the user gets a list of customers. If the result set is empty, let’s be considerate and give the user a message. We don’t want people to sit around wondering if the computer is ever going to process their request or not.

    with Selected as
       (select State, City, char(cusnum) as CusNum, LstNam
          from qiws.qcustcdt
         where State in ('MN', 'NY'))
    select State, City, CusNum, LstNam
      from (select State, City, CusNum, LstNam
              from Selected     
             union all
            select 'No data', ' ', ' ', ' '
              from Selected
            having count(*) = 0 ) as x (State, City, CusNum, LstNam)
    order by State
    

    Look at the difference. I moved the SELECT into a common table expression called Selected.

    with Selected as
       (select State, City, char(cusnum) as CusNum, LstNam
          from qiws.qcustcdt
         where State in ('MN', 'NY'))
    

    I chose to convert the number account number to character. That’s not necessary, but it will make the union a little smoother.

    Now query the common table expression:

    select State, City, CusNum, LstNam
      from (select State, City, CusNum, LstNam
              from Selected     
             union all
            select 'No data', ' ', ' ', ' '
              from Selected
            having count(*) = 0 ) as x (State, City, CusNum, LstNam)
    order by State
    

    The FROM clause unions two SELECT statements. The first reads the data in Selected, and so may or may not return a result set. The second one returns a result set of one row if the common table expression is empty.

    select 'No data', ' ', ' ', ' '
      from Selected
    having count(*) = 0
    

    This statement may look a little funny to you. It has a HAVING clause without a GROUP BY. In such a case, the entire input set (here, common table expression Selected) is treated as one group, and the SELECT clause can only have literals and aggregate functions. If it bothers you that GROUP BY is missing, you can add this one:

    group by ()
    

    If the result set comes up empty, the grid shows this:

    State City CusNum LstNam
    No data

    The effect is that one, and only one, of the two SELECT statements returns data.

    Works for me.

    RELATED STORIES

    The State of the UNION

    Grouping a Union

    Using UNION for Data Analysis

    SQL Facts Of UNION And ORDER BY

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Tags: Tags: 400guru, IBM i, SQL

    Sponsored by
    WorksRight Software

    Do you need area code information?
    Do you need ZIP Code information?
    Do you need ZIP+4 information?
    Do you need city name information?
    Do you need county information?
    Do you need a nearest dealer locator system?

    We can HELP! We have affordable AS/400 software and data to do all of the above. Whether you need a simple city name retrieval system or a sophisticated CASS postal coding system, we have it for you!

    The ZIP/CITY system is based on 5-digit ZIP Codes. You can retrieve city names, state names, county names, area codes, time zones, latitude, longitude, and more just by knowing the ZIP Code. We supply information on all the latest area code changes. A nearest dealer locator function is also included. ZIP/CITY includes software, data, monthly updates, and unlimited support. The cost is $495 per year.

    PER/ZIP4 is a sophisticated CASS certified postal coding system for assigning ZIP Codes, ZIP+4, carrier route, and delivery point codes. PER/ZIP4 also provides county names and FIPS codes. PER/ZIP4 can be used interactively, in batch, and with callable programs. PER/ZIP4 includes software, data, monthly updates, and unlimited support. The cost is $3,900 for the first year, and $1,950 for renewal.

    Just call us and we’ll arrange for 30 days FREE use of either ZIP/CITY or PER/ZIP4.

    WorksRight Software, Inc.
    Phone: 601-856-8337
    Fax: 601-856-9432
    Email: software@worksright.com
    Website: www.worksright.com

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    IBM i Security Expert Interprets PCI and Multi-Factor Authentication Of Course i’s Not The AS/400

    Leave a Reply Cancel reply

TFH Volume: 27 Issue: 47

This Issue Sponsored By

  • BCD
  • Profound Logic Software
  • OCEAN Tech Con 2017
  • Maxava
  • Manta Technologies

Table of Contents

  • Getting Hyperconverged On Power Systems
  • Of Course i’s Not The AS/400
  • Guru: Conditional SQL Unions
  • IBM i Security Expert Interprets PCI and Multi-Factor Authentication
  • Mixed Results For IT Spending Forecasts

Content archive

  • The Four Hundred
  • Four Hundred Stuff
  • Four Hundred Guru

Recent Posts

  • Tool Aims To Streamline Git Integration For Old School IBM i Devs
  • IBM To Add Full System Replication And FlashCopy To PowerHA
  • Guru: Decoding Base64 ASCII
  • The Price Tweaking Continues For Power Systems
  • IBM i PTF Guide, Volume 27, Numbers 31 And 32
  • You Can Now Get IBM Tech Support For VS Code For i
  • Price Cut On Power S1012 Mini Since Power S1112 Ain’t Coming Until 2026
  • IBM i: Pro and Con
  • As I See It: Disruption
  • IBM i PTF Guide, Volume 27, Number 30

Subscribe

To get news from IT Jungle sent to your inbox every week, subscribe to our newsletter.

Pages

  • About Us
  • Contact
  • Contributors
  • Four Hundred Monitor
  • IBM i PTF Guide
  • Media Kit
  • Subscribe

Search

Copyright © 2025 IT Jungle