Oracle TRIM() Function
Oracle TRIM() is a built-in function that returns a string with any specified leading and trailing characters (by default, whitespace) removed.
Use LTRIM() to remove characters from the left side of a string, and RTRIM() to remove characters from the right side of a string.
Oracle TRIM() Syntax
Here is the syntax for the Oracle TRIM() function:
TRIM(str)
TRIM(trim_character FROM str)
TRIM({BOTH | LEADING | TRAILING} trim_character FROM str)
Here:
BOTHmeans to remove both leading and trailing characters.LEADINGmeans to remove only leading characters.TRAILINGmeans to remove only trailing characters.- If
{BOTH | LEADING | TRAILING}is not specified, the default isBOTH.
Parameters
str-
Required. The string to be processed. It can be a value of type
CHAR,VARCHAR2,NCHAR,NVARCHAR2,CLOB, orNCLOB. trim_character-
Optional. The prefix and suffix characters to remove. You can specify only one character. If
trim_characteris not specified, the default is a single space.
Return Value
The Oracle TRIM() function returns a string with any specified leading and trailing characters (by default, whitespace) removed.
If any of the arguments are NULL, TRIM() returns NULL.
Oracle TRIM() Examples
Here are several examples of using the Oracle TRIM() function.
Removing Whitespace
This statement shows how to use the Oracle TRIM() function to remove whitespace from both sides of ' Hello ':
SELECT
' Hello ' Origin,
TRIM(' Hello ') Result
FROM dual;
Output:
ORIGIN RESULT
______________ _________
Hello HelloRemoving Specified Characters
This statement shows how to use the Oracle TRIM() function to remove the _*# characters from both sides of '___Hello___':
SELECT
'___Hello___' Origin,
TRIM('_' FROM '___Hello___') Result
TRIM('_' FROM '___Hello___') Result
FROM dual;
Output:
ORIGIN RESULT
______________ _________
___Hello___ HelloBOTH vs LEADING vs TRAILING
This statement shows how BOTH, LEADING, and TRAILING work:
SELECT
'___Hello___' Origin,
TRIM(BOTH '_' FROM '___Hello___') BOTH,
TRIM(LEADING '_' FROM '___Hello___') LEADING,
TRIM(TRAILING '_' FROM '___Hello___') TRAILING
FROM dual;
Output:
ORIGIN BOTH LEADING TRAILING
______________ ________ ___________ ___________
___Hello___ Hello Hello___ ___HelloNULL Arguments
If any of the arguments are NULL, TRIM() returns NULL.
SET NULL 'NULL';
SELECT
TRIM(NULL) Result1,
TRIM(NULL FROM 'ABC') Result2,
TRIM('ABC' FROM NULL) Result3
FROM dual;
Output:
RESULT1 RESULT2 RESULT3
__________ __________ __________
NULL NULL NULLIn this example, we use the statement SET NULL 'NULL'; to display NULL values as the string 'NULL'.
Conclusion
Oracle TRIM() is a built-in function that returns a string with any specified leading and trailing characters (by default, whitespace) removed.