TRIM() in SQL
Removes leading and/or trailing spaces (or specified characters) from a string.
Syntax
Return type
TRIM() Function Example
What is TRIM() in SQL?
The TRIM()
function in SQL removes leading and/or trailing spaces (or specified characters) from a string. This is useful for cleaning up data, ensuring consistency in string comparisons, and avoiding issues caused by accidental white spaces in stored values. The function supports both LTRIM() (removing leading spaces) and RTRIM() (removing trailing spaces) in some databases. It is widely used across SQL systems like MySQL, PostgreSQL, SQL Server, and Oracle to format text fields, clean user input, and optimize string-based queries by ensuring uniformity in stored and retrieved data.
Parameters:
string: The input string to be trimmed
removal_string: Optional characters to remove (defaults to space)
LEADING/TRAILING/BOTH: Optional specification of where to trim
Example Use Cases:
-- Clean user input data
-- Remove specific characters
-- Normalize contact data
Notes:
Behavior: By default, removes spaces from both ends
Performance Considerations: Efficient for basic string cleaning
Version Info: Core SQL function, available in most DBMS versions
Error Handling:
Error: Returns NULL for NULL input
Supported Databases:
DBMS
Function / Syntax
Example
Behavior with NULL
MySQL
TRIM()
TRIM(' abc ')
Returns NULL
PostgreSQL
TRIM()
TRIM(BOTH FROM ' abc ')
Returns NULL
SQL Server
TRIM()
TRIM(' abc ')
Returns NULL
SQLite
TRIM()
TRIM(' abc ')
Returns NULL
BigQuery
TRIM()
TRIM(' abc ')
Returns NULL
Snowflake
TRIM()
TRIM(' abc ')
Returns NULL
Athena
TRIM()
TRIM(' abc ')
Returns NULL