MySQL LTRIM() Function

The LTRIM() function in MySQL is used to remove leading spaces (spaces at the beginning of a string) from a given string.


Syntax

LTRIM(string)

Parameters

Parameter Description
string Required. The string from which leading spaces will be removed.

Definition and Use

  • Purpose: The LTRIM() function removes only the spaces at the beginning of a string. It does not affect spaces that appear after the first non-space character.
  • Behavior:
    • If the string has leading spaces, they will be removed.
    • If the string does not have leading spaces, the string will remain unchanged.
    • This function only removes spaces and does not remove other types of whitespace characters like tabs or newline characters.

Usage Examples

Example 1: Basic Usage

Remove the leading spaces from the string " SQL Tutorial":

SELECT LTRIM("     SQL Tutorial") AS LeftTrimmedString;

Output:

LeftTrimmedString
SQL Tutorial

Explanation: The leading spaces before "SQL Tutorial" have been removed.


Example 2: Removing Leading Spaces from Column Values

Remove the leading spaces from the CustomerName column:

SELECT CustomerName, LTRIM(CustomerName) AS LeftTrimmedCustomerName
FROM Customers;

Output (example data):

CustomerName LeftTrimmedCustomerName
" John Smith" "John Smith"
" Alice Brown" "Alice Brown"

Explanation: Any leading spaces in the CustomerName column are removed.


Technical Details

  • Works In: From MySQL 4.0 onwards.
  • Return Type: Returns a string with the leading spaces removed.
  • String Manipulation: Only removes leading spaces and does not affect other characters in the string.

Applications

  1. Data Cleaning: Useful for cleaning up user input or imported data where unnecessary leading spaces might be present.
  2. Text Processing: Helps in normalizing strings before comparison or formatting.
  3. Database Integrity: Ensures uniformity in string values, particularly when storing data or preparing reports.

Key Notes

  • This function only removes spaces from the beginning of the string. To remove spaces from both ends, use the TRIM() function.
  • If there are no leading spaces in the string, the function simply returns the original string.

The LTRIM() function is ideal for cleaning up string values that have extra spaces at the beginning, ensuring consistent formatting in MySQL.


Was this article helpful?