TRIM() in MySQL — How It Works

What the MySQL TRIM() function does, with an example.

Published October 18, 2026

TRIM() removes leading and trailing spaces (or a specified character) from a string. LTRIM and RTRIM remove from one side.

How it works

Use TRIM(BOTH 'x' FROM str) for other characters.

Try it in MySQL

SELECT TRIM(' hi ')
hi
SELECT TRIM(LEADING '0' FROM '00042')
42
SELECT TRIM(BOTH '-' FROM '--a--')
a

Practical examples

Example 1

SELECT TRIM('  hi  ');
-- hi

Example 2

SELECT TRIM(LEADING '0' FROM '00042');
-- 42

Example 3

SELECT TRIM(BOTH '-' FROM '--a--');
-- a

Use it in a real query

SELECT id, TRIM('  hi  ') AS result
FROM your_table
LIMIT 10;

Common mistakes

  • Expecting TRIM to remove inner spaces.
  • Not trimming user input before saving.
  • Forgetting non-breaking spaces are not trimmed.

Key takeaways

  • TRIM() in one line: TRIM() removes leading and trailing spaces (or a specified character) from a string.
  • Try queries in a test database first.
  • Check NULL handling and data types.

FAQ

How do I remove inner spaces?

Use REPLACE(str, ' ', '').

Does TRIM() work in other databases?

Most have an equivalent, but names and syntax vary between MySQL, PostgreSQL, SQL Server and SQLite.

More SQL articles