Sub topic 8
Cleaning and padding with trim, lpad and rpad
This chapter assumes you can write basic SELECT, WHERE and GROUP BY queries, know how PostgreSQL treats NULL, and can run queries in psql or another SQL client. You should also know the character types text, varchar and char(n) from the first chapter.
Real data is rarely tidy. Names arrive with trailing spaces, codes lose their leading zeros, and imported files carry tabs and non-breaking spaces. PostgreSQL has a small family of functions for removing unwanted characters from the ends of a string (trimming) and for stretching a string to a fixed width (padding). This chapter covers both, plus the edge cases that surprise people.
The trim family
trim removes characters from the start, the end, or both ends of a string. By default it removes spaces.
SELECT trim(' hello ') AS both_ends,
trim(LEADING FROM ' hello') AS leading_only,
trim(TRAILING FROM 'hello ') AS trailing_only;This returns hello in all three columns. The SQL-standard syntax is trim([LEADING | TRAILING | BOTH] [characters] FROM string). If you leave out the direction, BOTH is used. If you leave out the characters, a single space is used.
PostgreSQL also provides function-style variants that take the string first and the set of characters second:
| Function | Removes from | Default character |
|---|---|---|
| `trim(BOTH ...)` or `btrim(string [, chars])` | both ends | space |
| `ltrim(string [, chars])` | start | space |
| `rtrim(string [, chars])` | end | space |
btrim, ltrim and rtrim are the older PostgreSQL spellings. Both styles do the same job, so pick one and use it consistently in a codebase.
Trimming a set of characters
The second argument is a set of characters, not a substring. This is the most common source of confusion with trim.
SELECT trim(BOTH 'x' FROM 'xxhixx') AS single_char,
btrim('xyxhixyx', 'xy') AS char_set,
ltrim('0001230', '0') AS no_leading_zeros,
rtrim('report.csv.csv', '.csv') AS surprising;The results are:
single_charishi.char_setishi. PostgreSQL strips any mix ofxandyfrom the ends until it reaches a character outside the set.no_leading_zerosis1230. The trailing zero is untouched becauseltrimonly works on the start.surprisingisreport. You might expectreport.csv, butrtrimremoves any trailing.,c,sorvcharacters, so it keeps stripping until it hitst.
PostgreSQL 18 and later also accept trim with a bytea argument, but for text columns the rules above apply in every supported version.
Trimming only removes what you name
By default, trim removes the space character (U+0020) only. Tabs, newlines, carriage returns and non-breaking spaces (U+00A0) are not removed. Data pasted from spreadsheets or web pages often contains them.
SELECT trim(E'\t hello \n') AS default_trim,
trim(E' \t\r\n' FROM E'\t hello \n') AS whitespace_set,
regexp_replace(E'\u00a0hello\u00a0', '^\s+|\s+$', '', 'g') AS regex_trim;default_trimkeeps the tab and newline, because only spaces were removed.whitespace_setishello, because the set includes space, tab, carriage return and newline.regex_trimishello. In PostgreSQL's regular expressions,\smatches Unicode whitespace in a UTF8 database with a suitable locale, which often includes the non-breaking space. If it does not in your setup, add\u00a0explicitly to the character class, for example[\s\u00a0].
For stubborn whitespace, test with octet_length or ascii() on the first and last character to see what is really there.
Trimming and NULL
Every function in this chapter returns NULL when its string argument is NULL. Trimming a NULL does not give an empty string. If you need a default, wrap the result in coalesce:
SELECT trim(NULL::text) AS is_null,
coalesce(trim(NULL::text), '') AS is_empty;Also note that trimming a string made only of spaces gives an empty string, not NULL. That matters when you test for missing values. The function nullif converts empty strings back to NULL:
SELECT nullif(trim(' '), '') AS cleaned;This returns NULL. The pattern nullif(trim(col), '') is a compact way to normalize blank input to NULL.
Padding with lpad and rpad
lpad adds characters on the left and rpad adds them on the right, until the string reaches the requested length.
SELECT lpad(7::text, 3, '0') AS padded,
rpad('ab', 5, '.') AS right_padded,
lpad('abc', 8, 'xy') AS multi_char_fill,
lpad('hello', 3, '*') AS truncated;The results are:
paddedis007.right_paddedisab....multi_char_fillisxyxyxabc. The fill string repeats and is cut off when the target length is reached.truncatedishel.
The last result is the important edge case. If the string is already longer than the target length, lpad and rpad do not leave it alone. They truncate it to the target length, and they cut from the right in both functions. So lpad('hello', 3, '*') gives hel, not llo. If you pad an identifier that can exceed the width, you can silently lose data.
If you omit the fill argument, a space is used. The length argument counts characters, not bytes, so accented characters are handled correctly in a UTF8 database.
SELECT lpad('é', 3, '*') AS accented;This returns **é, a string of three characters.
Padding numbers
lpad takes text, so convert numbers first. Writing lpad(7, 3, '0') works in current PostgreSQL versions because an implicit cast to text is available for the function's signature, but an explicit cast makes your intent clear:
SELECT lpad(42::text, 6, '0') AS invoice_no,
to_char(42, 'FM000000') AS via_to_char;Both columns return 000042. For numbers, to_char is often the better tool, because it can also handle decimals and thousands separators. lpad is better when the value is already text, such as a code that mixes digits and letters.
A related trap: if the number is negative, lpad(-5::text, 4, '0') gives 00-5, because the minus sign is just another character. Use to_char for signed numbers.
Padding to align report output
rpad is useful for fixed-width text exports or aligned output in psql:
SELECT rpad(name, 12, ' ') || lpad(price::text, 8, ' ') AS line
FROM (VALUES ('Keyboard', 49.5), ('Mouse', 19.99)) AS t(name, price);Each line is exactly 20 characters. If a name could exceed 12 characters, rpad would truncate it, so use left(name, 12) deliberately or check the maximum length first with max(char_length(name)).
char(n) and trailing spaces
The char(n) type pads values with spaces to length n when it stores them, but PostgreSQL treats those trailing spaces as insignificant in comparisons and removes them when casting to text or varchar.
SELECT 'ab'::char(5) = 'ab'::char(5) AS equal_char,
length('ab'::char(5)) AS length_char,
octet_length('ab'::char(5)) AS bytes_char,
'ab'::char(5)::text AS as_text;Here length returns 2 because trailing spaces are ignored, while octet_length returns 5 because the stored value includes them. The cast to text yields ab with the padding removed. This is one more reason the first chapter recommends text or varchar over char(n): you rarely want the database to pad for you, and when you do, lpad and rpad do it explicitly.
A cleaning workflow
You can combine these functions to normalize messy codes. Suppose a table of product codes contains values like ' 42 ', '0042' and 'A7', and you want every numeric code to be five digits wide:
SELECT code,
CASE
WHEN trim(code) ~ '^\d+$'
THEN lpad(trim(code), 5, '0')
ELSE upper(trim(code))
END AS normalized
FROM (VALUES (' 42 '), ('0042'), ('A7')) AS t(code);The result is 00042, 00042 and A7. The ~ operator tests the trimmed value against a regular expression, so only all-digit codes are padded. Because the cleaning is repeated in each branch, in a real table you may prefer to put trim(code) in a subquery or a LATERAL join so you write it once.
Applying trim on read is good for quick queries, but if the data should never contain stray whitespace, clean it where it enters. A CHECK constraint such as CHECK (name = trim(name)) rejects untidy values, and UPDATE t SET name = trim(name) WHERE name <> trim(name) repairs existing rows. The WHERE clause avoids rewriting rows that are already clean.
Summary of gotchas
- The character argument of
trim,btrim,ltrimandrtrimis a set, not a substring. - Default trimming removes only the space character, not tabs, newlines or non-breaking spaces.
lpadandrpadtruncate strings that are longer than the target length.- Trimming NULL gives NULL, and trimming a blank string gives an empty string.
- Negative numbers padded with
lpadput the zeros before the minus sign. char(n)pads on storage but ignores the padding inlengthand in casts totext.
Exercise
A column ref holds values such as ' 17', '0017' and '-3'. You run SELECT lpad(trim(ref), 4, '0') FROM t;. What does each row return, and which row is a problem? Then write a query that returns 'abc' from 'abc.txt.txt' without losing the 'abc' part, explaining why rtrim('abc.txt.txt', '.txt') is a poor choice here.
Show answer
The rows return '0017', '0017' and '00-3'. The third is a problem, because the minus sign is treated as an ordinary character and the zeros end up before it; use tochar on a numeric value instead. For the second part, rtrim('abc.txt.txt', '.txt') treats '.txt' as the set {'.', 't', 'x'} and strips every trailing character in that set. Here it happens to give 'abc', but it would also eat the final 't' of 'compact.txt' and return 'compac'. A safe query is SELECT regexpreplace('abc.txt.txt', '(\.txt)+$', ''); which removes only whole '.txt' suffixes and returns 'abc'.
Exercise
Write an UPDATE that removes leading and trailing spaces, tabs and newlines from the title column of a table articles, touching only rows that actually change, and turns titles that become empty into NULL.
Show answer
UPDATE articles SET title = nullif(btrim(title, E' \t\r\n'), '') WHERE title IS DISTINCT FROM nullif(btrim(title, E' \t\r\n'), '');