The main string trim function in SQL Server is TRIM(), which removes spaces from both the beginning and end of a string. For older versions or specific needs, LTRIM() removes leading spaces and RTRIM() removes trailing spaces.
Background: Why Trimming Matters in SQL Server
Data entered by users or imported from external sources often contains unwanted spaces. These spaces can cause failed joins, incorrect comparisons, and wasted storage. For example, a WHERE clause like WHERE LastName = 'Smith' will not match a value stored as 'Smith ' (with a trailing space). Trimming functions normalize such data, making queries more reliable.
SQL Server has provided LTRIM and RTRIM since early versions. Starting with SQL Server 2017, the TRIM function was introduced, offering a more convenient way to remove both sides at once and also allowing removal of other characters.
How TRIM, LTRIM, and RTRIM Work
All three functions return a character string with specified characters removed. They do not modify the original data; they return a new value.
- LTRIM (character_expression) – Removes leading spaces (spaces at the start).
- RTRIM (character_expression) – Removes trailing spaces (spaces at the end).
- TRIM ( [ characters FROM ] character_expression ) – Removes spaces from both ends by default. With the
FROMclause, you can specify other characters to remove (available in SQL Server 2017 and later).
Example:
SELECT LTRIM(' Hello') AS LeadingTrimmed, -- Returns 'Hello'
RTRIM('Hello ') AS TrailingTrimmed, -- Returns 'Hello'
TRIM(' Hello ') AS BothTrimmed; -- Returns 'Hello'
Using TRIM with Specific Characters
In SQL Server 2017 and later, TRIM can remove characters other than spaces. You specify the characters in a string literal. For example, to remove leading and trailing commas and periods:
SELECT TRIM(',.' FROM ',..Hello..,') AS TrimmedChars; -- Returns 'Hello'
This is useful for cleaning data that contains punctuation or special characters. Note that the characters parameter is a string containing each character to remove, not a pattern.
Choosing Between LTRIM, RTRIM, and TRIM
Which function you use depends on your SQL Server version and what you need to remove:
- If you are on SQL Server 2017 or later, use
TRIMfor most cases—it is concise and handles both sides. - If you are on an older version (2016 or earlier), use
LTRIMandRTRIMtogether:LTRIM(RTRIM(column)). - If you only need to remove spaces from one side, use
LTRIMorRTRIMdirectly. - If you need to remove non-space characters, use
TRIMwith theFROMsyntax (requires 2017+).
Common Problems and Misconceptions
A frequent misconception is that TRIM removes all whitespace characters like tabs or newlines. It does not—by default it only removes spaces (ASCII 32). To remove tabs or other whitespace, you must specify them explicitly. For example, to remove tabs and spaces:
SELECT TRIM(CHAR(9) + ' ' FROM ' Hello ') AS TrimmedWhitespace;
Another issue is that TRIM does not remove spaces inside the string, only from the ends. If you need to remove all spaces, you would use REPLACE(column, ' ', '').
Also, be aware that TRIM returns NULL if the input is NULL. This is consistent with most SQL Server string functions.
Performance and Index Usage
Using TRIM (or LTRIM/RTRIM) in a WHERE clause can prevent the query optimizer from using an index on that column. For example, WHERE TRIM(LastName) = 'Smith' forces a scan because the function must be applied to every row before comparison. To improve performance, consider storing data already trimmed, or use a computed column with an index if trimming is frequently needed.
If you must filter on trimmed values, you can create a computed column:
ALTER TABLE Persons ADD LastNameTrimmed AS TRIM(LastName);
CREATE INDEX IX_LastNameTrimmed ON Persons(LastNameTrimmed);
Then query WHERE LastNameTrimmed = 'Smith'.
Alternatives and Related Functions
Sometimes trimming alone isn’t enough. Consider these related functions:
- REPLACE – Replaces all occurrences of a substring. Useful for removing all spaces or specific characters.
- CHARINDEX and SUBSTRING – For extracting parts of a string after trimming.
- UPPER and LOWER – For case normalization, often used alongside trimming.
- STUFF – For deleting a part of a string and inserting another.
In some cases, you might want to trim only leading or trailing characters that are not spaces. The TRIM function with the FROM clause handles that, but for older versions you’d need a combination of REPLACE and LTRIM/RTRIM with careful logic.
Frequently Asked Questions
Does TRIM remove tabs or newlines in SQL Server?
By default, no. TRIM only removes spaces. To remove tabs (CHAR(9)) or newlines (CHAR(10) and CHAR(13)), you must specify them in the characters parameter, like TRIM(CHAR(9) + CHAR(10) + CHAR(13) + ' ' FROM column).
Can I use TRIM in SQL Server 2016?
No. The TRIM function was introduced in SQL Server 2017. For SQL Server 2016 and earlier, use LTRIM(RTRIM(column)) to remove spaces from both ends.
Why doesn’t my WHERE clause match even after trimming?
If you trimmed the column but still no match, check for non-breaking spaces (CHAR(160)) or other Unicode whitespace. TRIM only removes regular spaces. You can replace non-breaking spaces with REPLACE(column, CHAR(160), ' ') before trimming.
Does TRIM affect NULL values?
Yes. If the input is NULL, TRIM returns NULL. This is standard behavior for SQL Server string functions.
Is there a performance difference between TRIM and LTRIM+RTRIM?
In practice, the performance difference is negligible. The main performance concern is using any function on a column in a WHERE clause, which can prevent index seeks.
Can I use TRIM on a column in an UPDATE statement?
Yes. For example: UPDATE Persons SET LastName = TRIM(LastName). This permanently removes spaces from the stored data.
Related
- 6 Digit Random Number: How to Generate One
- STRING_SPLIT SQL Server Syntax & Examples
- Software for Data Entry: Top Tools Compared
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- XLOOKUP Formula in Excel: A Practical Step-by-Step GuideIn Excel for Microsoft 365, XLOOKUP finds a value in one range and returns the corresponding value from…
- COUNTIF Less Than Cell Value: Excel FormulaTo count cells in a range that are less than a value stored in another cell, use the…
- Excel FILTER Function: Multiple Criteria and ExamplesYes. In Microsoft Excel for Microsoft 365, use the FILTER function with multiplication (*) to require multiple conditions…
- Excel SUMIF Not Blank: Sum Values When Cells Have DataWith the cells to check in A2:A10 and the numbers to add in B2:B10, use =SUMIF(A2:A10,"<>",B2:B10) to sum…
- Excel IFERROR Function: Syntax, Examples, and TipsMicrosoft Excel’s IFERROR function returns a value you choose when a formula produces an error; otherwise, it returns…
- Excel Split Cell String by Delimiter: Formulas and ToolsIn Excel for Microsoft 365, split a cell’s text at a delimiter with TEXTSPLIT: if A2 contains red,blue,green,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.