TRIM

The SQL TRIM function is used to remove whitespace or specified characters from both sides or either side of a string. It is a commonly used function in SQL to manipulate and clean up data. The TRIM function takes a string expression as its input and returns the same string with the specified characters removed.

Syntax

The syntax for the TRIM function is as follows:

TRIM([direction] [characters FROM] string)

Here, direction specifies which side of the string to remove characters from, and can be either BOTH (both sides), LEADING (left side), or TRAILING (right side). characters is an optional parameter that specifies the characters to be removed from the string. If characters is not specified, the function removes all whitespace characters from the string.

Example

Here is an example of using the TRIM function to remove whitespace from both sides of a string:

SELECT TRIM('   hello world   ') AS trimmed_string;

This would return: hello world.

In this example, the TRIM function removes the leading and trailing whitespace from the string ‘ hello world ‘.

You can also use the TRIM function to remove specific characters from a string. For example, if you want to remove all occurrences of the character ‘a’ from the beginning of a string, you can use the following syntax:

SELECT TRIM('a' FROM 'aaabbbccc') AS trimmed_string;

This would return: bbbccc.

In this example, the TRIM function removes all leading occurrences of the character ‘a’ from the string ‘aaabbbccc’.

In conclusion, the SQL TRIM function is a useful tool for manipulating and cleaning up data in SQL. It allows you to remove whitespace or specific characters from a string, making it easier to work with and analyze.