TRIM Function - SQL
Overview
The TRIM function in SQL removes leading and trailing spaces from a string. It is useful for cleaning up input data by removing unnecessary whitespace.
Example:
SELECT
TRIM(' Hello ')
Syntax:
SELECT
TRIM(string_expression)
string_expression
is the string from which you want to remove leading and trailing spaces.
Sample Data:
department_id | first_name |
---|---|
3 | Frank |
2 | Jane |
3 | Ashley |
NULL | Glenn |
2 | Kelly |
1 | Richard |
1 | George |
5 | Kyle |
2 | James |
1 | Gustavo |
Example: Hard-coded value
In this example, we are removing the leading and trailing spaces from the string ‘ Hello ‘ for an output of ‘hello.’
Example: Query without the WHERE Statement
In this example, we are removing the leading and trailing spaces from the rows in the first_name column.
Example: Query with the WHERE Statement
In this example, we are removing the leading and trailing spaces from the rows in the first_name column where the department_id equals 1.