trim(text) — Remove leading and trailing characters
Last updated: 2026-11-04
trim(text) — Remove leading and trailing characters
trim() strips unwanted characters from both ends of a string — the first step when cleaning form input or importing data from outside systems. It removes whitespace by default, and leading / trailing / both plus a character set after FROM let you control exactly what is removed; btrim(), ltrim() and rtrim() are shorthand variants.
| Kind | function |
|---|---|
| Example Language | SQL |
📝 Syntax
trim([leading | trailing | both] [characters] from string text) → text
⚙️ Parameters
| string text | The string to trim. Type text. |
|---|---|
| characters text | Optional: the set of characters to strip from the ends. Defaults to whitespace. Type text. |
Returns:text — the trimmed string. Returns NULL for a NULL input.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
id | trimmed | trimmed_x | trimmed_leading
----+-----------+-------------+-----------------
1 | [alice] | [ alice ] | [alice ]
2 | [xxbobxx] | [bob] | [xxbobxx]
3 | [carol] | [ carol] | [carol]
(3 rows)
📌 Key Points
- Only the ends are trimmed; whitespace in the middle is left alone.
- trim(both 'x' from s) strips every consecutive x at both ends, not just the first one.
- A NULL input produces NULL.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QDoes trim() remove whitespace in the middle of a string?
ANo — trim() only touches the ends. To collapse inner whitespace use regexp_replace(s, '\s+', ' ', 'g').