Db2 TRIM

Summary: in this tutorial, you will learn how to use the Db2 TRIM() function to remove blanks or another specified character from the beginning, the end, or both ends of a string.

Overview of Db2 TRIM() function

The TRIM() function allows you to remove blanks or another specified character from the beginning, the end, or both ends of a string.

The following illustrates the syntax of the Db2 TRIM() function:

TRIM([LEADING | TRAILING | BOTH] strip_character FROM string)
Code language: SQL (Structured Query Language) (sql)

In this syntax:

 BOTH, LEADING, or TRAILING

determines whether the function should remove the strip_character from the beginning, the end, or from both ends of the string. The TRIM() function uses BOTH by default. It means that the function will remove the strip_character from the ends of the string.

 strip_character

Is a single character that represents the character to be removed. The strip_character defaults to blank.

 FROM string

Specifies the string from which you want to remove the strip_character.

Db2 TRIM() function examples

Let’s take some examples of using the TRIM() function

1) Using Db2 TRIM() function to remove leading blanks from a string example

This example uses the TRIM() function to remove leading blanks from the string ' a test string ':

SELECT 
    TRIM(LEADING FROM ' a test string ') result
FROM 
    sysibm.sysdummy1;
Code language: SQL (Structured Query Language) (sql)

Here is the result:

RESULT          
---------------
a test string  
Code language: SQL (Structured Query Language) (sql)

2) Using Db2 TRIM() function to remove trailing blanks from a string example

This example uses the TRIM() function to remove the trailing blanks from the string ' a test string ':

SELECT 
    TRIM(TRAILING FROM ' a test string ') result
FROM 
    sysibm.sysdummy1;
Code language: SQL (Structured Query Language) (sql)

The output is as follows:

RESULT          
--------------- 
 a test string  
Code language: SQL (Structured Query Language) (sql)

3) Using Db2 TRIM() function to remove both leading and trailing blanks from a string example

This example uses the TRIM() function to remove both leading and trailing blanks from the string ' a test string ':

SELECT 
    TRIM(BOTH FROM ' a test string ') result
FROM 
    sysibm.sysdummy1;
Code language: SQL (Structured Query Language) (sql)

The following shows output:

RESULT          
--------------- 
a test string   
Code language: SQL (Structured Query Language) (sql)

In this tutorial, you have learned how to use the Db2 TRIM() function to remove a specified character from the beginning, the end, or both ends of a string.

Was this tutorial helpful ?