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.
- Categoria
- Strings
- Returns
string- In this category
- 6 of 172
Sintaxe
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.
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sim | TRIM from SQL Server 2017; LEADING/TRAILING and LTRIM/RTRIM character arguments from 2022 |
| PostgreSQL | Sim | Supported under this name. |
| MySQL | Sim | LTRIM and RTRIM strip spaces only; use TRIM(LEADING 'x' FROM s) for other characters |
| SQLite | Sim | Supported under this name. |
| Oracle | Sim | Supported under this name. |
Exemplos
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'
Bom saber
- 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.
Related on SQLly
- Find blank strings mixed with NULLs Snippet
- Trim whitespace then remove duplicates Snippet
- Normalize whitespace in SQL Snippet
- Split a comma-separated field into rows in SQL Snippet
- Find duplicates hiding behind whitespace Snippet
- Find duplicate emails ignoring case Snippet
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.