Leading whitespace is a common issue when working with data. A leading whitespace is a space at the start of a string. In most cases, we don’t want any leading whitespace, and we will want to remove it before the data goes any further (whether that means being stored in the database, displayed to the user, or whatever).
Fortunately, SQL Server provides us with the LTRIM()
function that allows us to remove leading blanks from a given string.
Example
Here’s a basic example:
SELECT LTRIM(' Cat');
Result:
Cat
To make the effect more apparent, here’s an example of a trimmed string and an untrimmed string side-by-side. This example also includes multiple leading whitespaces – all of which are removed.
SELECT
' Cat' AS 'Not Trimmed',
LTRIM(' Cat') AS 'Trimmed';
Result:
Not Trimmed Trimmed ----------- ------- Cat Cat
It’s important to note that it’s only leading whitespace that’s trimmed when using this syntax. If there’s another character before the whitespace, the function will have no effect:
SELECT LTRIM('My Cat');
Result:
My Cat
However, as from SQL Server 2022, we can include a second argument to specify which characters to trim.
In our case, we can do this:
SELECT LTRIM('My Cat', 'My ');
Result:
Cat
However, when we do this, we need to include the space as one of the characters to trim. Omitting this will trim the specified characters, while leaving any whitespace intact:
SELECT LTRIM('My Cat', 'My');
Result:
------------ Cat
Similar Functions
You can also use RTRIM()
to remove trailing whitespace, and TRIM()
to remove spaces (or other characters) from both sides of the string.