The MySQL LPAD() function is used to left-pad a string with another string (usually spaces or other characters) to a specified length. It is especially useful when you need to format strings to a fixed width or align them in reports or tables.
Syntax:
LPAD(string, length, pad_string)
- string: The original string to be padded.
- length: The desired length of the resulting string.
- pad_string: The string used for padding. If this string is longer than needed, it is truncated to fit the length.
Example Usage:
-
Basic Example:
SELECT LPAD('123', 5, '0');Result:
'00123'- The string
'123'is padded on the left with'0'until its total length becomes 5.
- The string
-
Padd with multiple characters:
SELECT LPAD('abc', 10, '-');Result:
'------abc'- The string
'abc'is padded with'-'to make it 10 characters long.
- The string
-
Padding with a string longer than needed:
SELECT LPAD('abc', 10, 'abc');Result:
'abcabcabca'- The string
'abc'is used as the padding string and repeated to fill the length, resulting in'abcabcabca'.
- The string
-
Padding with spaces (default behavior):
SELECT LPAD('hello', 10);Result:
' hello'- By default, if no padding string is specified, spaces are used.
The LPAD() function is very useful when formatting outputs for reports, data displays, or when preparing strings for further processing.
No comments:
Post a Comment