SQL String Functions

SQL TRIM Function: Remove Leading/Trailing Spaces (All Databases)

SQL TRIM, LTRIM, RTRIM functions to remove whitespace and characters. Covers all databases with data cleaning examples.

Mar 12, 20263 min read

Overview

TRIM removes unwanted characters (usually spaces) from the start and/or end of a string. Essential for data cleaning and input normalization.

MySQL

-- Remove leading and trailing spaces:
SELECT TRIM('  Hello  ');           -- 'Hello'
SELECT LTRIM('  Hello  ');          -- 'Hello  '
SELECT RTRIM('  Hello  ');          -- '  Hello'

-- Remove specific characters:
SELECT TRIM(BOTH '.' FROM '...Hello...');  -- 'Hello'
SELECT TRIM(LEADING '0' FROM '00042');     -- '42'

-- Clean data on insert/update:
UPDATE users SET email = TRIM(LOWER(email));

PostgreSQL

-- Same functions:
SELECT TRIM('  Hello  ');            -- 'Hello'
SELECT LTRIM('  Hello  ');           -- 'Hello  '
SELECT RTRIM('  Hello  ');           -- '  Hello'

-- Remove specific characters:
SELECT TRIM(BOTH '.' FROM '...Hello...');  -- 'Hello'
SELECT TRIM(LEADING '0' FROM '00042');     -- '42'

-- BTRIM (trim from both sides, specific chars):
SELECT BTRIM('xxHelloxx', 'x');  -- 'Hello'

SQL Server

-- TRIM (SQL Server 2017+):
SELECT TRIM('  Hello  ');             -- 'Hello'
SELECT LTRIM('  Hello  ');            -- 'Hello  '
SELECT RTRIM('  Hello  ');            -- '  Hello'

-- Remove specific characters (SQL Server 2017+):
SELECT TRIM('.' FROM '...Hello...');  -- 'Hello'

-- Older versions use LTRIM + RTRIM:
SELECT LTRIM(RTRIM('  Hello  '));

Oracle

-- TRIM:
SELECT TRIM('  Hello  ') FROM DUAL;            -- 'Hello'
SELECT TRIM(LEADING ' ' FROM '  Hello') FROM DUAL;
SELECT TRIM(TRAILING ' ' FROM 'Hello  ') FROM DUAL;

-- Remove specific characters:
SELECT TRIM(BOTH '0' FROM '00042000') FROM DUAL;  -- '42'

-- LTRIM/RTRIM with character set:
SELECT LTRIM('xxxHello', 'x') FROM DUAL;  -- 'Hello'

Skip the Syntax Lookup

Instead of memorizing TRIM syntax for each database, describe what you need in plain English and let AI2SQL generate the correct query.

Try AI2SQL Free

No credit card required

Frequently Asked Questions

How do I remove spaces from a string in SQL?

Use TRIM(string) to remove leading and trailing spaces. Use LTRIM for leading only, RTRIM for trailing only. All databases support these functions.

Can TRIM remove characters other than spaces?

Yes. Use TRIM(BOTH 'char' FROM string) to remove specific characters. This works in MySQL, PostgreSQL, SQL Server 2017+, and Oracle.

Can AI2SQL help clean messy data?

Yes. Describe your data cleaning needs like 'trim spaces and lowercase all emails' and AI2SQL generates the correct query.

Generate SQL from Plain English

Stop looking up syntax. Describe what you need and AI2SQL writes the query.

Try AI2SQL Free

No credit card required