In MySQL, the LPAD()
function is used to left-pad a string with a specified set of characters, up to a certain length. This is often used to format strings, ensuring that they have a specific length by adding characters to the left side of the original string.
The basic syntax of the LPAD()
function is as follows:
sqlLPAD(str, length, padstr)
str
: The original string that you want to left-pad.length
: The length of the resulting string after padding.padstr
: The string or characters to use for padding. This is optional, and if not provided, it defaults to a space.
Here's an example:
sqlSELECT LPAD('123', 5, '0') AS padded_string;
This query will return the string '00123' because the original string '123' is left-padded with zeros to make the total length 5.
If the padstr
parameter is not provided, it defaults to a space character. For example:
sqlSELECT LPAD('abc', 6,' ') AS padded_string;
This query will return the string ' abc' because the original string 'abc' is left-padded with spaces to make the total length 6.
The LPAD()
function is useful in scenarios where you need to format strings to a specific length, such as when dealing with fixed-width data in a table or when creating formatted outputs.
No comments:
Post a Comment