Skip to main content

lpad

1. LPAD Function

The LPAD function in H2 database is used to left-pad a string with a specific character or set of characters to a specified length.

2. Syntax

The syntax for the LPAD function in H2 database is as follows:

LPAD(str, len, padstr)

Arguments

  • str: The input string that needs to be left-padded.
  • len: The desired length of the resulting string after left-padding.
  • padstr: The character or set of characters used for left-padding.

Return

  • The LPAD function returns a new string after left-padding the input string.

3. Notes

  • The length argument (len) must be a positive integer.
  • If the input string is already longer than the specified length, the LPAD function will truncate the string to the desired length.
  • If the padstr argument is not provided, the default padding character is a space (' ').
  • The LPAD function is case-sensitive, meaning that if you provide a padstr with multiple characters, the entire padstr will be used for padding, even if it exceeds the desired length.

4. Examples

Here are a few examples demonstrating the usage of the LPAD function in H2 database:

Example 1 - Left-padding a string with spaces:

SELECT LPAD('hello', 10) AS padded_string;

Output:

padded_string
-------------
hello

Example 2 - Left-padding a string with a specific character:

SELECT LPAD('world', 8, '*') AS padded_string;

Output:

padded_string
-------------
***world

Example 3 - Left-padding a string stored in a column:

CREATE TABLE words (
id INT PRIMARY KEY,
word VARCHAR(10)
);

INSERT INTO words VALUES (1, 'cat'), (2, 'dog'), (3, 'bird');

SELECT id, LPAD(word, 6, '-') AS padded_word
FROM words;

Output:

id | padded_word
---+------------
1 | ---cat
2 | ---dog
3 | --bird
  • rpad - Right-pad a string with a specific character or set of characters.
  • substring - Extract a substring from a string.