SQL Server LTRIM() Function

In SQL Server, the LTRIM() function is used to remove the leading spaces of a string and return the result. This function is useful for trimming the left side of a text string.

Syntax

The syntax for the LTRIM() function is as follows:

LTRIM(string_expression)

Here, string_expression is the string expression from which the leading spaces are to be removed.

Usage

The LTRIM() function is typically used to clean up data by removing leading and trailing spaces from strings before performing any operation on them. It can also be used to compare two strings after removing the leading spaces.

Examples

Here are two examples of using the LTRIM() function.

Example 1

Query all customer names from a table but ignore the leading spaces in their names.

SELECT LTRIM(CustomerName) AS TrimmedName
FROM Customers

Assuming the Customers table contains the following data:

CustomerName
ABC Inc.
XYZ Corp.
Smith & Co.

The query result will be:

TrimmedName
ABC Inc.
XYZ Corp.
Smith & Co.

Example 2

Compare two strings using the LTRIM() function and ignore the leading spaces.

DECLARE @str1 VARCHAR(20) = '  Hello'
DECLARE @str2 VARCHAR(20) = 'Hello  '

SELECT CASE
         WHEN LTRIM(@str1) = LTRIM(@str2) THEN 'Strings are equal'
         ELSE 'Strings are not equal'
       END AS Result

The query result will be:

Result
Strings are equal

Conclusion

The LTRIM() function is a useful function that helps remove the leading spaces of a text string. It can be used to clean up data by removing leading spaces from strings before performing any operation on them. Using it can make SQL queries more concise and reduce errors caused by unnecessary spaces.