Sub topic 8
Cleaning and Padding with `trim`, `lpad` and `rpad`
This chapter assumes that you know SELECT, expressions, PostgreSQL text types, and NULL. The examples use text values directly, so you can run them without creating a table.
Text often contains unwanted spaces or needs a fixed display width. PostgreSQL provides trim for removing characters from the ends of a string, and lpad and rpad for adding characters to reach a requested length.
Removing characters from the ends
trim removes characters from the beginning, the end, or both ends of a string. With no character list, it removes spaces.
SELECT
trim(' PostgreSQL ') AS default_trim,
trim(LEADING FROM ' PostgreSQL ') AS without_left_spaces,
trim(TRAILING FROM ' PostgreSQL ') AS without_right_spaces,
trim(BOTH FROM ' PostgreSQL ') AS without_both_spaces;The keywords LEADING, TRAILING, and BOTH select the side to clean. BOTH is the default.
You can provide a character list with FROM. PostgreSQL removes matching characters repeatedly from the selected ends. It does not search for one exact substring.
SELECT
trim(BOTH 'x' FROM 'xxhixx') AS remove_x,
ltrim('---title---', '-') AS remove_left_dashes,
rtrim('---title---', '-') AS remove_right_dashes,
btrim('---title---', '-') AS remove_both_dashes;This returns hi, title---, ---title, and title. The functions ltrim, rtrim, and btrim are convenient alternatives when the side is fixed.
A common mistake is trimming data before deciding whether spaces are meaningful. For example, spaces might be part of a fixed-width code or a user-entered value. Clean values at a deliberate boundary, such as during import or presentation.
Adding padding
lpad adds characters on the left, and rpad adds them on the right. Their first argument is the source string, and their second argument is the target length.
SELECT
lpad('42', 5, '0') AS account_code,
rpad('SQL', 8, '.') AS label,
lpad('abc', 2, '0') AS shortened;The results are 00042, SQL....., and ab. If the source is already longer than the target, PostgreSQL truncates it. This behavior makes padding useful for display output, but dangerous when the target length is a validation limit. Use a separate length check when truncation would lose data.
The fill value can contain more than one character. PostgreSQL repeats it as needed and cuts the final repetition to fit.
SELECT
lpad('7', 8, 'ab') AS left_filled,
rpad('ok', 7, '-=') AS right_filled;lpad and rpad count characters, not raw UTF-8 bytes. A NULL source or fill value produces NULL, so handle missing values with coalesce when a visible result is required.
Exercise
What does lpad('A', 4, '0') return, and what does lpad('ABCDE', 4, '0') return?
Show answer
It returns 000A for the first expression and ABCD for the second, because lpad fills short values and truncates long values.