MySQL LPAD() Function

The LPAD() function in MySQL adds a specified string to the left side of an existing string until the combined string reaches a certain length. This is helpful for formatting strings to a consistent length or for padding strings with leading characters.



LPAD(): Definition and Usage

LPAD() is used to left-pad strings, meaning it adds characters to the beginning of the string. This is often necessary for formatting purposes or to create strings of a consistent length. If the original string is already longer than the target length, LPAD() will truncate the original string from the right.

Syntax

Syntax

LPAD(string, length, pad_string)
      

Parameter Values

Parameter Description
string The original string. This is required.
length The desired final length of the string after padding. If the original string is longer, the string is truncated from the right to this length. This is required.
pad_string The string used for padding (added to the left of the original string). This is required.

Examples

Padding a String Literal

This example pads the string "SQL Tutorial" on the left with "ABC" until it reaches a length of 20 characters.

Syntax

SELECT LPAD("SQL Tutorial", 20, "ABC");
      
Output

ABCA BCA BCA SQL Tutorial
      

Padding Strings from a Column

This example pads the 'CustomerName' column from the 'Customers' table with "ABC" to a total length of 30 characters (assuming a 'Customers' table exists with a 'CustomerName' column).

Syntax

SELECT LPAD(CustomerName, 30, "ABC") AS LeftPadCustomerName
FROM Customers;
      
Output

LeftPadCustomerName
-------------------
(Each CustomerName left-padded with "ABC" to a length of 30 characters)
      

**Note:** In the second example, the output will vary depending on the contents of your `Customers` table. Each `CustomerName` will be padded to 30 characters using "ABC". If a `CustomerName` is already longer than 30 characters, it will be truncated from the right to fit the 30-character limit.