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)