TRIM()
SQL · String Functions
Theory
TRIM(string) removes spaces from both the start and the end of a string; spaces in the middle are kept. TRIM(' Asha ') returns 'Asha', and TRIM(' Asha Rao ') returns 'Asha Rao'. The standard form also lets you say which side and which character: TRIM(LEADING '0' FROM code), TRIM(TRAILING '.' FROM x) or TRIM(BOTH '*' FROM x).
Dialects differ in syntax. Postgres, MySQL, Oracle and SQL Server accept the standard TRIM(... FROM ...) form. SQLite and Postgres also accept TRIM(string, characters), where every character listed is stripped, so TRIM('**Asha**', '*') returns 'Asha'. Plain TRIM removes only the ordinary space, not tabs or line breaks in most databases, which is a common reason why values still look padded after trimming. Invisible padding makes 'Asha ' and 'Asha' different values, so joins and GROUP BY quietly fail until you TRIM both sides.
Why we use it
Spaces sneak in from Excel uploads, forms and fixed-width files. They are invisible on screen but make equal values compare as different, break joins and inflate distinct counts. TRIM removes them.
When to use it
Use TRIM when cleaning imported or user-entered text, and on both sides of a join key that might be padded. Use LTRIM or RTRIM when only one side should be cleaned. For tabs and newlines, list them explicitly or use REGEXP_REPLACE.
How it works
- Take the string (and optional characters to strip)
- Remove matching characters from the start until a different one appears
- Remove matching characters from the end the same way
- Characters in the middle are never touched
- Return the trimmed string
Syntax
TRIM(string)Example
SELECT TRIM(' Asha ');
-- 'Asha'Key points
- Removes from both ends only; inner spaces stay
- Standard form: TRIM(BOTH|LEADING|TRAILING 'x' FROM str)
- SQLite/Postgres also accept TRIM(str, 'chars')
- Plain TRIM usually ignores tabs and newlines
- Very commonly used to clean imported/user-entered data