SIGN UP MEMBER LOGIN:
   
ARTICLE

How to Trim a string in SQL

Posted by Sapna Articles | SQL Server July 05, 2010
Tags: TRIM, SQL
In this article you will know how to trim a string in SQL.
Reader Level:


When running more complex queries, such as concatenating strings, often times you may need to trim whitespace from the values. The TRIM function in SQL is used to remove specified prefix or suffix from a string. The most common pattern being removed is white spaces. This function is called differently in different databases:

  • MySQL:           TRIM(), RTRIM(), LTRIM()
  • Oracle:            RTRIM(), LTRIM()
  • SQL Server:     RTRIM(), LTRIM()

The syntax for these trim functions are:

TRIM([[LOCATION] [remstr] FROM ] str): [LOCATION] can be either LEADING, TRAILING, or BOTH. This function gets rid of the [remstr] pattern from either the beginning of the string or the end of the string, or both. If no [remstr] is specified, white spaces are removed.

LTRIM(str): Removes all white spaces from the beginning of the string.

RTRIM(str): Removes all white spaces at the end of the string.

Example:

SELECT TRIM('   HELLO   ');

Result:

'HELLO'


Example 2:

SELECT LTRIM('   HELLO   ');

Result:

'HELLO   '


Example 3:

SELECT RTRIM('   HELLO   ');

Result:

'   HELLO'

Login to add your contents and source code to this article
This Feature is Sponsored By
post comment
COMMENT USING