// strings reference

SQL TRIM function

Removes leading or trailing characters, spaces by default. The usual cleaner for pasted CSV values and form input; engines differ on which characters you can strip and from which side.

Category
Strings
Returns
string
In this category
6 of 172

Syntax

TRIM(string)
TRIM([LEADING | TRAILING | BOTH] 'chars' FROM string)
LTRIM(string, chars)

Each block is a separate form. The support table and the examples show which engine takes which.

Engine support

EngineSupportNotes
SQL Server Yes TRIM from SQL Server 2017; LEADING/TRAILING and LTRIM/RTRIM character arguments from 2022
PostgreSQL Yes Supported under this name.
MySQL Yes LTRIM and RTRIM strip spaces only; use TRIM(LEADING 'x' FROM s) for other characters
SQLite Yes Supported under this name.
Oracle Yes Supported under this name.

Examples

Any engine

SELECT TRIM('  padded  ') AS tight;  -- 'padded'

PostgreSQL

SELECT TRIM(BOTH ',' FROM ',a,b,,') AS stripped;  -- 'a,b'

Oracle

SELECT LTRIM('000123', '0') AS n FROM dual;  -- '123'

Good to know

  • Plain TRIM removes spaces only, not tabs or newlines, on every engine. Strip those with REGEXP_REPLACE, or by naming them: TRIM(BOTH E'\t\n ' FROM s) on PostgreSQL.
  • SQL Server 2017 added TRIM('chars' FROM s) for both ends; LEADING and TRAILING, and the second argument to LTRIM and RTRIM, arrived in SQL Server 2022.
  • Oracle treats '' as NULL, so RTRIM(' ') returns NULL, not an empty string.
  • LTRIM(s, chars) and RTRIM(s, chars) work on PostgreSQL, SQLite, Oracle and SQL Server 2022+. MySQL's LTRIM and RTRIM take one argument and strip spaces only.

Questions about TRIM / LTRIM / RTRIM

Does TRIM remove tabs and newlines?

No. Plain TRIM removes only spaces. On PostgreSQL, REGEXP_REPLACE(s, '^\s+|\s+$', '', 'g') strips all leading and trailing whitespace. On SQL Server, TRIM(CHAR(9) + CHAR(10) + CHAR(13) + ' ' FROM s) names the characters to strip.

What is the difference between TRIM, LTRIM and RTRIM?

TRIM strips both ends, LTRIM the left, RTRIM the right. TRIM also takes LEADING or TRAILING to do one side, and on most engines a set of characters to strip instead of spaces.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.