• The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
Menu
  • The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
  • Use SQL To Change A Substring

    February 9, 2016 Ted Holt

    Occasionally I need to change part of a string value in a database table. SQL has three mechanisms that let me accomplish such a thing. Do you know what those three mechanisms are and how to use them?

    First, we need a table for illustrative purposes.

    create table Parts
      ( ID            char(6)       primary key,
        Description   varchar(40),
        Cost          dec (5,2),
        Price         dec (5,2));
    
    insert into parts values                         
    ('XX-101', '20-inch Doodad',            0.12,    0.25),
    ('XX-105', '2-foot Doodad left-hand',   0.48,    0.75),
    ('XX-106', '2-foot Doodad right-hand',  0.48,    0.75),
    ('XX-118', '12-foot Doodad',            1.25,    3.00),
    ('BA-101', '5CM  Widget',               0.30,    0.45),
    ('BA-104', '15Cm Widget',               1.00,    1.35),
    ('BA-111', '150cm Widget',              5.00,    8.00),
    ('BA-145', 'Used 15cm Widget',          0.20,    0.80),
    ('CT-201', 'ACME chain stretcher',      4.75,   19.99),
    ('CT-202', 'Refurbished ACME sky hook', 3.00,   12.00);
    

    Mechanism 1: Substring and Concatenation

    You can use the substring function and concatenation to build a new value for a string. This method is appropriate when you know where the substring begins.

    For example, some of the parts have IDs that begin with “XX”. Let’s change “XX” to “AA”.

    update parts                        
       set ID = 'AA' concat substr(ID,3)
     where ID between 'XX' and 'XX9'    
    

    I concatenated the string “AA” to the third and following characters of the ID and assigned the result back to the ID column.

    Now the table looks like this:

    ID

    DESCRIPTION

    AA-101

    20-inch
    Doodad

    AA-105

    2-foot
    Doodad left-hand

    AA-106

    2-foot
    Doodad right-hand

    AA-118

    12-foot
    Doodad

    BA-101

    5CM Widget

    BA-104

    15Cm Widget

    BA-111

    150cm Widget

    BA-145

    Used 15cm
    Widget

    CT-201

    ACME chain
    stretcher

    CT-202

    Refurbished
    ACME sky hook

    The string that is to be replaced and the replacement string do not have to be the same length. That happened to be the case in this example.

    Mechanism 2: The REPLACE Function

    When you don’t know where a substring will begin, you can use the REPLACE function to replace one string with another. Let’s replace the barbaric term “doodad” with the more elegant and urbane term “doohickey”.

    update parts 
       set Description = replace(Description, 'Doodad', 'Doohickey')
     where ID between 'AA' and 'AA9'
    

    Look at the descriptions now.

    ID

    Description

    AA-101

    20-inch
    Doohickey

    AA-105

    2-foot
    Doohickey left-hand

    AA-106

    2-foot
    Doohickey right-hand

    AA-118

    12-foot
    Doohickey

    BA-101

    5CM Widget

    BA-104

    15Cm
    Widget

    BA-111

    150cm
    Widget

    BA-145

    Used 15cm
    Widget

    CT-201

    ACME chain
    stretcher

    CT-202

    Refurbished
    ACME sky hook

    The WHERE clause was not necessary, but including it prevented SQL from updating other rows unnecessarily.

    Mechanism 3: Regular Expressions

    Regular expressions are a cryptic but powerful type of wild card processing. To learn more about them, read Michael Sansoterra’s superb explanation.

    Let’s change the parts that are measured in centimeters in two ways. First, let’s make sure that the abbreviation for centimeter, cm, is in lowercase letters. Second, let’s leave only one space between cm and the following text. Here’s the update:

    update parts as p                                              
       set p.description = regexp_replace(p.description,           
                                    '([0-9]+)[Cc][Mm]( +)','$1cm ')
     where regexp_like (p.description,'[0-9]+[Cc][Mm]')            
    

    Look at the table now:

    ID

    Description

    AA-101

    20-inch
    Doohickey

    AA-105

    2-foot
    Doohickey left-hand

    AA-106

    2-foot
    Doohickey right-hand

    AA-118

    12-foot
    Doohickey

    BA-101

    5cm
    Widget

    BA-104

    15cm
    Widget

    BA-111

    150cm
    Widget

    BA-145

    Used 15cm
    Widget

    CT-201

    ACME chain
    stretcher

    CT-202

    Refurbished
    ACME sky hook

    The WHERE clause uses the regular expression like function to select the rows that have a number immediately followed by the letters “CM” in any case. Look more closely.

    where regexp_like (p.description,'[0-9]+[Cc][Mm]')
    
    • [0-9] matches any digit.
    • + means to match one or more occurrences of the preceding match. This prevents the system from selecting the ACME parts for update.
    • [Cc] tells the system to match on the letter C regardless of case.
    • [Mm] tells the system to match on the letter M regardless of case.

    The regular expression replace function changes part of the string.

    regexp_replace(p.description, '([0-9]+)[Cc][Mm]( +)','$1cm ') 
    
    • ( indicates the beginning of the first capturing group.
    • [0-9] matches any digit.
    • + means to match one or more occurrences of the preceding match.
    • ) indicates the end of the first capturing group.
    • [Cc] tells the system to match on the letter C regardless of case.
    • [Mm] tells the system to match on the letter M regardless of case.
    • ( indicates the beginning of the second capturing group.
    • The blank tells the system to look for a blank character.
    • + means to match one or more occurrences of the preceding match.
    • ) indicates the end of the second capturing group.

    When such a match is found, the system uses the third parameter to replace the matched text.

    • $1 means to include the contents of the first capturing group, which consists of the digits preceding the letters CM.
    • The letters “cm” and one blank are to be placed into the string following the first capturing group.
    • The second capturing group, which contains the blanks following “CM”, is not referenced, so the system does not include it in the replacement string.

    The remainder of the description is not part of the match, and is therefore not affected.

    So there you have it. Three replacement mechanisms. If you need to replace part of a string, you can handle it.

    RELATED STORY

    Native Regular Expressions In DB2 For i 7.1 And 7.2

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Tags:

    Sponsored by
    Computer Keyes

    Fax Directly from your IBM i

    KeyesFax is a full function automated IBM i fax system. Spooled files are burst by fax number and auto transmitted with overlays.  It combines both a send and receive facsimile processing system with a complete image package.

    The fax software will edit, send, receive, display, print, and track fax documents or images using any standard IBM i without additional expensive hardware, software or subscriptions.

    Computer Keyes has been developing Software Solutions since 1978!

    www.computerkeyes.com

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Sponsored Links

    COMMON:  2016 Annual Meeting & Expo, May 15 - 18, in New Orleans! Great Power Systems event!
    System i Developer:  RPG & DB2 Summit - March 22-24 in Dallas. Register by Feb 12 and save $300!
    BCD:  IBM i eBook: Top 10 Reasons to Choose PHP. Download now »

    IBM Patches OpenSSH Security Flaws That Impact IBM i IBM Wheels And Deals On Big Iron Compute And Memory

    Leave a Reply Cancel reply

Volume 16, Number 03 -- February 9, 2016
THIS ISSUE SPONSORED BY:

Bug Busters Software Engineering
ProData Computer Services
WorksRight Software

Table of Contents

  • IBM i and .Net Connectivity With XMLSERVICE
  • Use SQL To Change A Substring
  • Parsing Delimited Text Data Natively In SQL, Part 2: Java To The Rescue

Content archive

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

Recent Posts

  • IBM Unveils Manzan, A New Open Source Event Monitor For IBM i
  • Say Goodbye To Downtime: Update Your Database Without Taking Your Business Offline
  • i-Rays Brings Observability To IBM i Performance Problems
  • Another Non-TR “Technology Refresh” Happens With IBM i TR6
  • IBM i PTF Guide, Volume 27, Number 18
  • Will The Turbulent Economy Downdraft IBM Systems Or Lift It?
  • How IBM Improved The Database With IBM i 7.6
  • Rocket Celebrates 35th Anniversary As Private Equity Owner Ponders Sale
  • 50 Acres And A Humanoid Robot With An AI Avatar
  • IBM i PTF Guide, Volume 27, Number 17

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