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 basic syntax of a LTRIM is as follows:
SELECT LTRIM(string);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 upIf you are looking for another good reference, you can check here: https://docs.docker.com/samples/aspnet-mssql-compose/.
The simple example is to remove leading spaces from a string literal.
select ltrim(' Hello World!') as result;| result |
|---|
| Hello World! |
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 |
