Published on

January 3, 2013

Understanding TRIM Function in SQL Server

Trimming leading and trailing spaces from strings is a common operation in SQL Server. However, unlike some other databases, SQL Server does not have a built-in TRIM function. If you try to use the TRIM function in SQL Server, it will throw an error.

For example, consider the following script:

DECLARE @String1 NVARCHAR(MAX)
SET @String1 = ' String '
SELECT TRIM(@String1) TrimmedValue

Executing the above script will result in the following error:

Msg 195, Level 15, State 10, Line 4
'TRIM' is not a recognized built-in function name.

So, how can we achieve the same result as the TRIM function in SQL Server? SQL Server provides two functions that can be nested to achieve the desired result:

  1. RTRIM – Removes the spaces on the right side (or leading spaces) of the string.
  2. LTRIM – Removes the spaces on the left side (or trailing spaces) of the string.

By combining these two functions, we can effectively trim the leading and trailing spaces from a string without encountering any errors. Here’s an example:

DECLARE @String1 NVARCHAR(MAX)
SET @String1 = ' String '
SELECT @String1 OriginalString, RTRIM(LTRIM(@String1)) TrimmedValue

In addition to using the RTRIM and LTRIM functions directly, you can also create a user-defined function that encapsulates these functions. This can be useful if you frequently need to perform trimming operations in your queries. Here’s an example of creating a TRIM function:

CREATE FUNCTION dbo.TRIM(@string VARCHAR(MAX))
RETURNS VARCHAR(MAX)
BEGIN
RETURN LTRIM(RTRIM(@string))
END

Now, you can use the TRIM function just like any other built-in function in SQL Server:

SELECT dbo.TRIM(' String ')

It’s important to note that using functions, including the TRIM function, in the WHERE clause can negatively impact query performance. When a function is used in the WHERE clause, SQL Server has to process the function on the entire column, leading to table or index scans instead of index seeks. This can result in poor performance and increased resource utilization. Therefore, it’s recommended to use functions judiciously and only when necessary to enforce business needs.

In conclusion, while SQL Server does not have a built-in TRIM function, you can achieve the same result by combining the RTRIM and LTRIM functions or by creating a user-defined function. Just remember to be mindful of using functions in the WHERE clause to avoid performance issues.

Thank you for reading! Stay tuned for more SQL Server tips and tricks.

Click to rate this post!
[Total: 1 Average: 5]

Let's work together

Send us a message or book free introductory meeting with us using button below.