How to use LTRIM in Sql Server

05.17.2022

Intro

SQL Server provides the LTRIM function to remove leading white space. In this article, we will learn how to use LTRIM in SQL Server.

The Syntax

The basic syntax of a LTRIM is as follows:

SELECT LTRIM(string);
  • string: The string or varchar you want to remove leading white space.

Getting Setup

For this, we will be using docker. This is recommended for more than just using SQL Server. To find how to install docker go here: https://docs.docker.com/engine/install/

Now create a file called docker-compose.yml and add the following.

version: "3.9"
services:
  db:
    image: "mcr.microsoft.com/mssql/server"
    ports: 
      - 1433:1433
    environment:
        SA_PASSWORD: "Your_password123"
        ACCEPT_EULA: "Y"

Open a terminal and go to the folder the file is located. Then run the following.

docker-compose up

If you are looking for another good reference, you can check here: https://docs.docker.com/samples/aspnet-mssql-compose/.

Basic Example

The simple example is to remove leading spaces from a string literal.

select ltrim('   Hello World!') as result;
result
Hello World!

Lower on a Table Column

We can also run lower on a column. Below we create an employee table where the names have extra white space.

CREATE TABLE employees (
    first_name VARCHAR (50) NOT NULL,
    last_name VARCHAR (50) NOT NULL
);

insert into employees (first_name, last_name) 
	values 
	(' Keith', 'Holliday'),
	('   Jon', 'Doe'),
	('  Jane', 'Doe');

We can now run the ltrim function on the columns.

select 
  ltrim(first_name) as FirstName,
	ltrim(last_name) as LastName
from employees e;
FirstName LastName
Keith Holliday
Jon Doe
Jane Doe