We are all acquainted with the TRIM() function, which effectively eliminates leading and trailing spaces from a provided string. However, were you aware that there are additional variations available?
1) The default TRIM(str)
For the default variation, we just need to pass the string we wish to be trimmed as the parameter. This returns the string with all leading and trailing spaces removed.
SELECT TRIM(' trim ');
-> 'trim'
2) Removing leading and trailing characters
If we want to trim specific characters other than empty spaces, we can use a different variation of the TRIM()
function by passing the character(s) we want to remove along with the keyword BOTH
. The syntax for this variation would be, TRIM(BOTH 'c' FROM 'str')
.
SELECT TRIM(BOTH '.' FROM '...trim...');
-> 'trim'
3) Removing leading characters/spaces
Now if we want to do the same thing as 2 but only remove the leading characters we would have to simply replace the BOTH
keyword with LEADING
.
SELECT TRIM(LEADING '.' FROM '...trim...');
-> 'trim...'
We can also use this to remove leading spaces but LTRIM(str)
is a separate function that can also be used in such cases.
SELECT LTRIM(' trim ');
-> 'trim '
4) Removing trailing characters/spaces
Similarly, if we want to remove trailing characters or spaces, we can use different variations of the TRIM() function. To remove specific characters, we would use the keyword TRAILING
instead of "LEADING". For removing spaces, you can use the RTRIM()
function instead of LTRIM().
SELECT TRIM(TRAILING'.' FROM '...trim...');
-> '...trim'
SELECT LTRIM(' trim ');
-> ' trim'
Thank you for taking the time to read this content. If you found it informative and valuable, please consider liking and commenting. Stay tuned for more!