Inserts, NULLs and Cleanup

What does trim() do in SQL?

TRIM() removes spaces from the start and end of text by default. See what it does, how it differs across databases, and how to clean empty-looking values.

On this page
  1. The short answer
  2. Removing other characters
  3. Cleaning values that look empty
  4. What TRIM() doesn’t do
  5. Where it fits

The short answer

TRIM() removes characters from the start and end of a string. By default it removes spaces only, and spaces inside the text are left alone.

SELECT TRIM('   Oak Street   ') AS street;
-- Returns 'Oak Street'

Removing other characters

Some databases let you name the characters to remove and the side to trim. In MySQL:

SELECT TRIM(LEADING '0' FROM '000417');   -- Returns '417'
SELECT TRIM(TRAILING '!' FROM 'Hello!!'); -- Returns 'Hello'

In SQL Server, the basic TRIM() works from SQL Server 2017. Removing other characters needs SQL Server 2022 or later, and the LEADING, TRAILING and BOTH keywords also need database compatibility level 160. In older versions, LTRIM() removes spaces from the start and RTRIM() removes them from the end. By default, TRIM() is equivalent to LTRIM(RTRIM()).

Cleaning values that look empty

A value made of spaces only isn’t NULL, so IS NULL won’t find it, even though it looks blank. Trim the values, and turn the ones that end up empty into NULL:

UPDATE customers
SET middle_name = NULLIF(TRIM(middle_name), '')
WHERE TRIM(middle_name) = '';

Decide first whether your application should store empty values as NULL or as empty strings, and use one approach throughout.

What TRIM() doesn’t do

  • It doesn’t remove tabs or line breaks by default. Those are different characters from spaces, so name them explicitly where your database allows it.
  • NULL in gives NULL out. MySQL and SQL Server both return NULL when the input is NULL, so TRIM() can’t fill a blank by itself.

Where it fits

For the text types that TRIM() works on, see different data types of sql. To fill the NULL values themselves, see what is coalesce() in sql.

The complete guide to inserts, nulls and cleanup

How to Insert Values Into an Empty Column in SQL
Read the guide

Keep exploring

Guides from other topics

All topics →