// 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.

Kategorie
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-Unterstützung

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

Beispiele

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'

Gut zu wissen

  • 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.