In SQL Server, we can use the T-SQL LTRIM()
function to remove leading blanks from a given string.
Also, as from SQL Server 2022, we can specify other leading characters to remove from the string.
Syntax
The basic syntax prior to SQL Server 2022 goes like this:
LTRIM ( character_expression )
Where character_expression
is an expression of character or binary data. It can be any constant, variable, or column (as long as it’s of a data type, except text, ntext, and image, that is implicitly convertible to varchar).
As from SQL Server 2022, the syntax is as follows:
LTRIM ( character_expression , [ characters ] )
Where characters is a literal, variable, or function call of any non-LOB character type (nvarchar, varchar, nchar, or char) containing characters that should be removed. nvarchar(max) and varchar(max) types aren’t allowed.
This syntax requires that the database compatibility level is set to 160.
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
Specify the Leading Characters
From SQL Server 2022, we can include a second argument that lists the leading characters to remove. This requires that the database compatibility level is set to 160.
Example:
SELECT LTRIM('GoodCat', 'Good');
Result:
Cat
Here’s an example that shows how the results can differ, depending on the characters we provide:
DECLARE @a char(7) = 'GoodCat';
SELECT
LTRIM(@a, 'God') AS 'God',
LTRIM(@a, 'dog') AS 'dog',
LTRIM(@a, 'odg') AS 'odg',
LTRIM(@a, 'od') AS 'od',
LTRIM(@a, 'do') AS 'do',
LTRIM(@a, 'og') AS 'og',
LTRIM(@a, 'go') AS 'go';
Result:
God dog odg od do og go ------- ------- ------- ------- ------- ------- ------- Cat Cat Cat GoodCat GoodCat dCat dCat
Similar Functions
You can also use RTRIM()
to remove trailing characters, and TRIM()
to remove spaces (or other characters) from both sides of the string.