The TRIM function removes either or both leading or trailing
spaces, numbers, or characters from any character value
expression. SQL returns the specified string minus any leading
or trailing characters (or both).
The BOTH option is the default if none is specified. The space
character is the default if a string is not specified.
The character value expression that you trim must be defined
as data type CHAR, VARCHAR, NCHAR, or NCHAR VARYING. Use the
CAST function to convert other data types before using the TRIM
function.
SQL returns a run-time error when the trim character is not
exactly one character in length.
Examples: Using the TRIM function
Example 1: The following example, though not effective, shows the
TRIM function:
SQL> SELECT LAST_NAME,
cont> TRIM (LEADING 'H' FROM LAST_NAME)
cont> FROM EMPLOYEES
cont> WHERE LAST_NAME LIKE 'H%';
LAST_NAME
Hall all
Harrington arrington
Harrison arrison
Hastings astings
Herbener erbener
5 rows selected
Example 2: Using the TRIM function with the WHERE clause
SQL> -- The following INSERT statement helps to show the
SQL> -- TRIM function.
SQL> --
SQL> INSERT INTO EMPLOYEES (LAST_NAME,FIRST_NAME,EMPLOYEE_ID) VALUES
cont> (' Hillson','Ann','99999');
1 row inserted
SQL> --
SQL> -- If you select columns without specifying the
SQL> -- TRIM function on the WHERE clause, SQL returns only those
SQL> -- last names that start with 'H' and have no leading spaces.
SQL> --
SQL> SELECT LAST_NAME || ', ' || FIRST_NAME
cont> FROM EMPLOYEES
cont> WHERE LAST_NAME LIKE 'H%';
Hall , Lawrence
Harrington , Margaret
Harrison , Lisa
Hastings , Norman
Herbener , James
5 rows selected
SQL> --
SQL> -- Add the TRIM function to the WHERE clause to get a complete
SQL> -- list of last names beginning with 'H' including those with
SQL> -- leading spaces.
SQL> --
SQL> SELECT LAST_NAME || ', ' || FIRST_NAME
cont> FROM EMPLOYEES
cont> WHERE TRIM (LEADING ' ' FROM LAST_NAME) LIKE 'H%';
Hastings , Norman
Harrington , Margaret
Hall , Lawrence
Harrison , Lisa
Hillson , Ann
Herbener , James
6 rows selected
Example 3: Using the TRIM function on the SELECT portion of a
query in addition to the WHERE clause
SQL> -- Add the TRIM function to the SELECT portion of the query
SQL> -- to trim the leading spaces from the display of 'Hillson'.
SQL> -- Note that the LEADING option has been changed to the BOTH
SQL> -- option to trim leading and trailing spaces from the
SQL> -- LAST_NAME column.
SQL> --
SQL> SELECT TRIM (BOTH ' ' FROM LAST_NAME) || ', ' || FIRST_NAME
cont> FROM EMPLOYEES
cont> WHERE TRIM (LEADING ' ' FROM LAST_NAME) LIKE 'H%';
Hastings, Norman
Harrington, Margaret
Hall, Lawrence
Harrison, Lisa
Hillson, Ann
Herbener, James
6 rows selected