StringsSQL standard

TRIM

Removes spaces (or other characters) at the start and end of a string.

Syntax

TRIM(<text>)
TRIM(LEADING <characters> FROM <text>)
TRIM(TRAILING <characters> FROM <text>)
TRIM(BOTH <characters> FROM <text>)

Without extra words it removes spaces from both ends. LEADING — only at the start, TRAILING — only at the end, BOTH — from both sides. Most often it's used to clean up what people typed: ' Emma ' from a form is no longer 'Emma' when you compare.

Spaces on both sides
SELECT TRIM(' Emma ') AS trimmed,
LENGTH(' Emma ') AS length_before,
LENGTH(TRIM(' Emma ')) AS length_after;
trimmedlength_beforelength_after
Emma104

Spaces aren't visible in the result table, so their lengths are shown next to it: there were 10 characters, 4 are left.

Only one side, and not spaces
SELECT TRIM(LEADING '0' FROM '000123') AS no_zeros,
TRIM(TRAILING '.' FROM 'Hello...') AS no_dots;
no_zerosno_dots
123Hello

Watch out

The second argument is a set of characters, not a word: TRIM(BOTH 'ab' FROM 'abba_x_ba') strips every a and b from the edges and gives _x_.

Without arguments it removes only ordinary spaces — tabs and line breaks stay. For those, list the characters explicitly: TRIM(E' \t\n' FROM <text>).

TRIM doesn't touch spaces inside the string: 'Emma Wilson' keeps its three spaces.

Related functions

LTRIMRTRIMREPLACE

Learn more in the course