SQL LTRIM()

The SQL LTRIM() function removes any leading spaces (spaces at the beginning) from a given string. It is useful for cleaning up data, especially when working with user inputs or fixed-width data that might contain unnecessary spaces at the start of strings.

The LTRIM() function is widely supported in SQL databases, including SQL Server, MySQL, PostgreSQL, and Oracle.

In this tutorial, we will go through SQL LTRIM() String function, its syntax, and how to use this function in SQL statements for string operations, with the help of well detailed examples.


Syntax of SQL LTRIM() Function

The basic syntax of the SQL LTRIM() function is:

</>
Copy
LTRIM(string);

Each part of this syntax has a specific purpose:

  • string: The text from which to remove leading spaces. This can be a column, variable, or text literal.

The LTRIM() function returns the string with any leading spaces removed.


Setup for Examples: Creating the Database and Table

We’ll create a sample products table with fields product_name and description to demonstrate the LTRIM() function examples.

1. First, create a new database called store:

</>
Copy
CREATE DATABASE store;

2. Select the store database to work with:

</>
Copy
USE store;

3. Create a table named products with fields product_id, product_name, and description:

</>
Copy
CREATE TABLE products (
    product_id INT PRIMARY KEY AUTO_INCREMENT,
    product_name VARCHAR(100),
    description TEXT
);

4. Insert sample data into the products table to use with the LTRIM() function examples:

</>
Copy
INSERT INTO products (product_name, description)
VALUES 
('  Laptop Pro', '   High-performance laptop with a sleek design.'),
('Wireless Mouse  ', 'Compact and easy to use.   '),
('  Smartphone XL', '   Large screen smartphone with powerful features.'),
('Tablet', 'Versatile tablet for work and play.');

With this setup complete, you can run the LTRIM() function examples to test and view results in the products table.