Sidebar

The Case for SQL CASE

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

SQL CASE expressions are powerful. Understand their syntax and where they can be used.

 

Did you know that the SQL CASE construct can be used in SQL SELECT and UPDATE statements and in WHERE, GROUP BY, and ORDER BY clauses? This tip explains SQL CASE through examples that you can run and experiment with. It also gives an overview of SQL CASE syntax, though it does not attempt to rewrite the IBM DB2 for i SQL Reference manual.

SQL CASE Syntax

There are SQL CASE expressions and SQL CASE statements. An expression can be slotted in where a value is needed. A statement allows you to execute different SQL statements, usually UPDATE or DELETE statements. In this tip, I will cover only SQL CASE expressions.

 

An SQL CASE construct consists of one or more "WHEN conditions THEN result" parts and an optional "ELSE result" part.

 

There can be a simple when clause, where the value is set before the first WHEN keyword is executed, or a searched when clause, where the value is determined as the WHEN keyword is executed.

 

Example of a Simple When Clause

  case state

      when 'CA' then 'California'

      when 'TX' then 'Texas'

      else 'Also Rans'

  end

 

In this example, all the decisions are based on the value in field "state," which is determined before the first WHEN is executed.

 

Example of a Searched When Clause

  case when City = 'Hector' then 150

       when Zipcod > 90000 then 200

       else 300

  end

 

In this example, decisions are made on the City field and the Zipcod field, which are evaluated when each WHEN is executed.

 

Both of the above examples are SQL CASE expressions, in that they provide values.

Running the Examples

The examples in this tip are based on file QIWS/QCUSTCDT, which I believe by default is available on almost everyone's machine, unless you have deleted it. It contains just 12 records and some of the data looks like this:

 

CUSNUM   LSTNAM    CITY    STATE  ZIPCOD   CDTLMT     BALDUE

938,472   Henning   Dallas   TX    75,217    5,000      37.00

839,283   Jones     Clay     NY    13,041      400     100.00

392,859   Vine      Broton   VT     5,046      700     439.00

938,485   Johnson   Helen    GA    30,545    9,999   3,987.50

397,267   Tyron     Hector   NY    14,841    1,000        .00

389,572   Stevens   Denver   CO    80,226      400      58.75

846,283   Alison    Isle     MN    56,342    5,000      10.00

475,938   Doe       Sutter   CA    95,685      700     250.00

693,829   Thomas    Casper   WY    82,609    9,999        .00

593,029   Williams  Dallas   TX    75,218      200      25.00

192,837   Lee       Hector   NY    14,841      700     489.50

583,990   Abraham   Isle     MN    56,342    9,999     500.00

 

To run any of the examples, cut and paste into your favorite SQL client. I have formatted the code for clarity, but be aware that your client's paste function may not retain the formatting I have used. Sometimes words may run together, especially in green-screen clients. To avoid this problem, I have tried to keep a blank at the beginning of each code line, which hopefully will make it through the conversion to HTML. I expect you will have fewer difficulties if you use Run SQL Scripts in iSeries Navigator or another GUI client, such as the open-source SQuirreL.

SQL CASE in SELECT Statements

Let's say we want to spell out some of the state names and put in a default value for the others. We could use a SELECT statement like this, with a simple when clause:

 

 Select  state,

         case state

            when 'CA' then 'California'

            when 'NY' then 'New York'

            when 'TX' then 'Texas'

            else 'Also Rans'

         end StateName

 from    qiws/qcustcdt

 

 

We would get this result:

 

  STATE  STATENAME  

   TX    Texas      

   NY    New York   

   VT    Also Rans  

   GA    Also Rans  

   NY    New York   

   CO    Also Rans  

   MN    Also Rans  

   CA    California 

   WY    Also Rans  

   TX    Texas      

   NY    New York   

   MN    Also Rans  

 

Here, the SQL CASE builds a new column (field) from a constant. "StateName" after the "end" gives a name to the column we generated.

 

Let's look at a searched when clause. We want to count how many customers there are in each of three balance-due ranges: up to $250, $250–$500, and over $500. This select statement does the job:

 

 SELECT

    sum(case when baldue between    .01 and 250 then 1 else 0 end) Lt250,

    sum(case when baldue between 250.01 and 500 then 1 else 0 end) Lt500,

    sum(case when baldue >= 500.01              then 1 else 0 end) Other

 FROM qiws/qcustcdt

 

 

Each "when" sets a value of either 1 or 0 for the enclosing "sum" function. It may look a bit strange, but if balance due is $37.00, then the first "when" resolves to "sum(1) as Lt250."

 

The result of the SELECT is a single row:

 

        LT250           LT500           OTHER

            6               3               1

SQL CASE in a SELECT Statement WHERE Clause

Maybe we want to see customers whose balance due is greater than 35 percent of their credit limit, with the added wrinkle that in New York it is 40 percent of their credit limit. We can put that into the WHERE clause, like this:

 

 Select   cusnum, lstnam, state, cdtlmt, baldue,

          decimal(baldue/cdtlmt*100,7,2) bal_ratio

 from     qiws/qcustcdt

 where    baldue > cdtlmt *

             case when state = 'NY' then .40

                  else                   .35

             end

 order by state

 

 This result is produced:

 

  CUSNUM   LSTNAM    STATE  CDTLMT     BALDUE   BAL_RATIO

 475,938   Doe        CA       700     250.00       35.71

 938,485   Johnson    GA     9,999   3,987.50       39.87

 192,837   Lee        NY       700     489.50       69.92

 392,859   Vine       VT       700     439.00       62.71

SQL CASE in an Order By Clause

We want a list of customers by state, showing descending balances due in each state, but with the exception that we want Texas first, followed by California, then New York, and finally all the rest by state.

 

In this SELECT statement, the first field in the ORDER BY clause is unnamed and is generated by the SQL CASE expression:

 

 Select   state, cusnum, lstnam, baldue

 from     qiws/qcustcdt

 order by case state

             when 'TX' then 1

             when 'CA' then 2

             when 'NY' then 3

             else         999

          end, state, baldue desc

 

These are the results:

 

  STATE   CUSNUM   LSTNAM      BALDUE

   TX    938,472   Henning      37.00

   TX    593,029   Williams     25.00

   CA    475,938   Doe         250.00

   NY    192,837   Lee         489.50

   NY    839,283   Jones       100.00

   NY    397,267   Tyron          .00

   CO    389,572   Stevens      58.75

   GA    938,485   Johnson   3,987.50

   MN    583,990   Abraham     500.00

   MN    846,283   Alison       10.00

   VT    392,859   Vine        439.00

   WY    693,829   Thomas         .00

SQL CASE in a Group By Clause

You can also code SQL CASE in a group by clause. If we wanted to see our total exposure for balances up to $250, balances $250–$500, and balances above $500, we could run an SQL statement like this:

 

 SELECT

    case when baldue between    .01 and 250 then '0-250'

         when baldue between 250.01 and 500 then '251-500'

         else '500+'

    end Bal_Range,

    sum(baldue) Exposure

 FROM qiws/qcustcdt

 WHERE baldue > 0 

 group by

    case when baldue between    .01 and 250 then '0-250'

         when baldue between 250.01 and 500 then '251-500'

         else '500+'

    end

 order by 1

 

It produces results like this:

 

   BAL_RANGE                                   EXPOSURE

    0-250                                        480.75

    251-500                                    1,428.50

    500+                                       3,987.50

 

This isn't a perfect solution, because you need to repeat the SQL CASE code. This following code gives the same results using a Common Table Expression. It still uses SQL CASE, but not in the GROUP BY clause.

 

 with mydata as (

   select

      case when baldue between    .01 and 250 then '0-250'

           when baldue between 250.01 and 500 then '251-500'

           else                                    '500+'

     end Bal_Range,

    baldue

   FROM qiws/qcustcdt

 )

 select   Bal_range, sum(baldue) Exposure

 from     myData

 where    baldue > 0

 group by Bal_Range

 order by 1

 

SQL CASE in an Update Statement

To encourage settlement of balances due, we might decide to give those in Texas a 10 percent discount, those in California a 20 percent discount, and everyone else a 30 percent discount. We can do this with an SQL CASE expression in the SET clause of an update statement.

 

First, for this demo, let's create temporary table MyDemo so we don't update QIWS/QCUSTCDT:

 

  create table qtemp/MyDemo as

  (Select * FROM qiws/qcustcdt) with data

 

 Now we can run this code where SQL CASE provides the discount percentage based on the state:

 

 update qtemp/MyDemo

 set baldue = baldue - baldue *

    case state

       when 'TX' then .10

       when 'CA' then .20

       else           .30

    end

 where baldue > 0

 

 This will update 10 rows.

Conclusion

The SQL CASE construct is powerful and convenient. It is well worth becoming familiar with its capabilities and syntax. There is not room in this tip to cover everything it can do, but you should have enough information to experiment further. If you're ambitious, try using SQL CASE in a JOIN predicate.

Notes

I ran these examples on the free V5R3 machine at http://www.rzkh.de, but SQL CASE has been available since at least V4R5, so most should be able to use it.

 

I have formatted the example code because I find it much easier to read and debug. However, SQL does not require such formatting.

 

Sam Lennon

Sam Lennon is an analyst, developer, consultant and IBM i geek. He started his programming career in 360 assembly language on IBM mainframes, but moved to the AS400 platform in 1991 and has been an AS400/iSeries/i5/IBM i advocate ever since.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

RESOURCE CENTER

  • WHITE PAPERS

  • WEBCAST

  • TRIAL SOFTWARE

  • White Paper: Node.js for Enterprise IBM i Modernization

    SB Profound WP 5539

    If your business is thinking about modernizing your legacy IBM i (also known as AS/400 or iSeries) applications, you will want to read this white paper first!

    Download this paper and learn how Node.js can ensure that you:
    - Modernize on-time and budget - no more lengthy, costly, disruptive app rewrites!
    - Retain your IBM i systems of record
    - Find and hire new development talent
    - Integrate new Node.js applications with your existing RPG, Java, .Net, and PHP apps
    - Extend your IBM i capabilties to include Watson API, Cloud, and Internet of Things


    Read Node.js for Enterprise IBM i Modernization Now!

     

  • Profound Logic Solution Guide

    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 companyare not aligned with the current IT environment.

    Get your copy of this important guide today!

     

  • 2022 IBM i Marketplace Survey Results

    Fortra2022 marks the eighth edition of the IBM i Marketplace Survey Results. Each year, Fortra captures data on how businesses use the IBM i platform and the IT and cybersecurity initiatives it supports.

    Over the years, this survey has become a true industry benchmark, revealing to readers the trends that are shaping and driving the market and providing insight into what the future may bring for this technology.

  • Brunswick bowls a perfect 300 with LANSA!

    FortraBrunswick is the leader in bowling products, services, and industry expertise for the development and renovation of new and existing bowling centers and mixed-use recreation facilities across the entertainment industry. However, the lifeblood of Brunswick’s capital equipment business was running on a 15-year-old software application written in Visual Basic 6 (VB6) with a SQL Server back-end. The application was at the end of its life and needed to be replaced.
    With the help of Visual LANSA, they found an easy-to-use, long-term platform that enabled their team to collaborate, innovate, and integrate with existing systems and databases within a single platform.
    Read the case study to learn how they achieved success and increased the speed of development by 30% with Visual LANSA.

     

  • The Power of Coding in a Low-Code Solution

    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:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks

     

     

  • Why Migrate When You Can Modernize?

    LANSABusiness 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.
    In this white paper, you’ll learn how to think of these issues as opportunities rather than problems. We’ll explore motivations to migrate or modernize, their risks and considerations you should be aware of before embarking on a (migration or modernization) project.
    Lastly, we’ll discuss how modernizing IBM i applications with optimized business workflows, integration with other technologies and new mobile and web user interfaces will enable IT – and the business – to experience time-added value and much more.

     

  • UPDATED: Developer Kit: Making a Business Case for Modernization and Beyond

    Profound Logic Software, Inc.Having trouble getting management approval for modernization projects? The problem may be you're not speaking enough "business" to them.

    This Developer Kit provides you study-backed data and a ready-to-use business case template to help get your very next development project approved!

  • What to Do When Your AS/400 Talent Retires

    FortraIT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators is small.

    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:

    • Why IBM i skills depletion is a top concern
    • How leading organizations are coping
    • Where automation will make the biggest impact

     

  • Node.js on IBM i Webinar Series Pt. 2: Setting Up Your Development Tools

    Profound Logic Software, Inc.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. In Part 2, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Attend this webinar to learn:

    • Different tools to develop Node.js applications on IBM i
    • Debugging Node.js
    • The basics of Git and tools to help those new to it
    • Using NodeRun.com as a pre-built development environment

     

     

  • Expert Tips for IBM i Security: Beyond the Basics

    SB PowerTech WC GenericIn this session, IBM i security expert Robin Tatam provides a quick recap of IBM i security basics and guides you through some advanced cybersecurity techniques that can help you take data protection to the next level. Robin will cover:

    • Reducing the risk posed by special authorities
    • Establishing object-level security
    • Overseeing user actions and data access

    Don't miss this chance to take your knowledge of IBM i security beyond the basics.

     

     

  • 5 IBM i Security Quick Wins

    SB PowerTech WC GenericIn today’s threat landscape, upper management is laser-focused on cybersecurity. You need to make progress in securing your systems—and make it fast.
    There’s no shortage of actions you could take, but what tactics will actually deliver the results you need? And how can you find a security strategy that fits your budget and time constraints?
    Join top IBM i security expert Robin Tatam as he outlines the five fastest and most impactful changes you can make to strengthen IBM i security this year.
    Your system didn’t become unsecure overnight and you won’t be able to turn it around overnight either. But quick wins are possible with IBM i security, and Robin Tatam will show you how to achieve them.

  • Security Bulletin: Malware Infection Discovered on IBM i Server!

    SB PowerTech WC GenericMalicious programs can bring entire businesses to their knees—and IBM i shops are not immune. It’s critical to grasp the true impact malware can have on IBM i and the network that connects to it. Attend this webinar to gain a thorough understanding of the relationships between:

    • Viruses, native objects, and the integrated file system (IFS)
    • Power Systems and Windows-based viruses and malware
    • PC-based anti-virus scanning versus native IBM i scanning

    There are a number of ways you can minimize your exposure to viruses. IBM i security expert Sandi Moore explains the facts, including how to ensure you're fully protected and compliant with regulations such as PCI.

     

     

  • Encryption on IBM i Simplified

    SB PowerTech WC GenericDB2 Field Procedures (FieldProcs) were introduced in IBM i 7.1 and have greatly simplified encryption, often without requiring any application changes. Now you can quickly encrypt sensitive data on the IBM i including PII, PCI, PHI data in your physical files and tables.
    Watch this webinar to learn how you can quickly implement encryption on the IBM i. During the webinar, security expert Robin Tatam will show you how to:

    • Use Field Procedures to automate encryption and decryption
    • Restrict and mask field level access by user or group
    • Meet compliance requirements with effective key management and audit trails

     

  • Lessons Learned from IBM i Cyber Attacks

    SB PowerTech WC GenericDespite the many options IBM has provided to protect your systems and data, many organizations still struggle to apply appropriate security controls.
    In this webinar, you'll get insight into how the criminals accessed these systems, the fallout from these attacks, and how the incidents could have been avoided by following security best practices.

    • Learn which security gaps cyber criminals love most
    • Find out how other IBM i organizations have fallen victim
    • Get the details on policies and processes you can implement to protect your organization, even when staff works from home

    You will learn the steps you can take to avoid the mistakes made in these examples, as well as other inadequate and misconfigured settings that put businesses at risk.

     

     

  • The Power of Coding in a Low-Code Solution

    SB PowerTech WC GenericWhen 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:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks

     

     

  • The Biggest Mistakes in IBM i Security

    SB Profound WC Generic The Biggest Mistakes in IBM i Security
    Here’s the harsh reality: cybersecurity pros have to get their jobs right every single day, while an attacker only has to succeed once to do incredible damage.
    Whether that’s thousands of exposed records, millions of dollars in fines and legal fees, or diminished share value, it’s easy to judge organizations that fall victim. IBM i enjoys an enviable reputation for security, but no system is impervious to mistakes.
    Join this webinar to learn about the biggest errors made when securing a Power Systems server.
    This knowledge is critical for ensuring integrity of your application data and preventing you from becoming the next Equifax. It’s also essential for complying with all formal regulations, including SOX, PCI, GDPR, and HIPAA
    Watch Now.

  • Comply in 5! Well, actually UNDER 5 minutes!!

    SB CYBRA PPL 5382

    TRY 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.

    Request your trial now!

  • Backup and Recovery on IBM i: Your Strategy for the Unexpected

    FortraRobot automates the routine 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:
    - Simplified backup procedures
    - Easy data encryption
    - Save media management
    - Guided restoration
    - Seamless product integration
    Make sure your data survives when catastrophe hits. Try the Robot Backup and Recovery Solution FREE for 30 days.

  • Manage IBM i Messages by Exception with Robot

    SB HelpSystems SC 5413Managing messages on your IBM i can be more than a full-time job if you have to do it manually. 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:
    - Automated message management
    - Tailored notifications and automatic escalation
    - System-wide control of your IBM i partitions
    - Two-way system notifications from your mobile device
    - Seamless product integration
    Try the Robot Message Management Solution FREE for 30 days.

  • Easiest Way to Save Money? Stop Printing IBM i Reports

    FortraRobot 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:

    - Automated report distribution
    - View online without delay
    - Browser interface to make notes
    - Custom retention capabilities
    - Seamless product integration
    Rerun another report? Never again. Try the Robot Report Management Solution FREE for 30 days.

  • Hassle-Free IBM i Operations around the Clock

    SB HelpSystems SC 5413For over 30 years, Robot has been a leader in systems management for IBM i.
    Manage your job schedule with the Robot Job Scheduling Solution. Key features include:
    - Automated batch, interactive, and cross-platform scheduling
    - Event-driven dependency processing
    - Centralized monitoring and reporting
    - Audit log and ready-to-use reports
    - Seamless product integration
    Scale your software, not your staff. Try the Robot Job Scheduling Solution FREE for 30 days.