Here are detailed examples of how to use the LPAD function in Oracle:
# Syntax
- length: The total length of the string after padding.
- pad_string: Optional. The string to pad the original string with. If omitted, spaces are used by default.
Pad the string 'Hello' to a total length of 10 using spaces.
-- Returns ' Hello'
# 2. Padding with
a Specific Character
Pad the string 'Hello' to a total length of 10 using the asterisk (*) character.
-- Returns '*Hello'
# 3. Padding with
a Multi-Character String
Pad the string 'Hello' to a total length of 12 using the characters 'ab'.
-- Returns 'ababababHello'
# 4. Truncating
the Original String
If the length specified is shorter than the original string, the original string is truncated to that length.
SELECT LPAD('HelloWorld', 5) AS padded_string FROM DUAL;
-- Returns 'Hello'
# 5. Padding
Numbers
Convert a number to a string and pad it with leading zeros to a total length of 10.
-- Returns '0000012345'
# 6. Combining
with Other Functions
Pad the result of another function, such as SUBSTR.
-- Returns '##Ora'
# 7. Padding
Within Table Columns
Pad values in a column of a table. Assume we have a table employees with a column employee_id:
# Practical Use Cases
Ensure that all string values are aligned when generating reports.
Generate codes or identifiers of fixed length.
# 3. Formatting
Numbers
Format numbers with leading zeros for consistent presentation.
# Additional Examples
Pad a username to a length of 15 characters.
-- Returns ' john_doe'
# 2. Padding a
String with a Character
Pad 'Data' with hyphens to a total length of 10.
-- Returns '------Data'
# 3. Padding a
Column in a Table
Assume we have a table products with a column product_code. Pad each product code with leading zeros to a length of 6.
Pad the result of a concatenation.
-- Returns 'Item123'
# 5. Padding with
Multi-Character String
Pad 'Report' with 'xyz' to a total length of 12.
-- Returns 'xyzxyzReport'
These examples illustrate how to use the LPAD function to pad strings to a desired length with various characters, ensuring consistency and alignment in data presentation.