TRIM
In SQL, the TRIM
command removes leading and trailing spaces or specified characters from a string.
Syntax
TRIM([remove_chars] FROM string)
remove_chars
(Optional): The characters to be removed. If omitted, the function removes spaces by default.string
: The string from which characters or spaces will be removed.
Example
Here’s a table users
to be used in this example:
username |
---|
‘ john_doe ‘ |
‘ alice_123 ‘ |
‘ admin ‘ |
Here’s another table products
to be used in this example as well:
product_code |
---|
‘#AB123#’ |
‘##XY456##’ |
‘#LM789#’ |
The example below demonstrates how to remove leading and trailing spaces from the username
column in the users
table:
SELECT username, TRIM(username) AS cleaned_usernameFROM users;
In this example, the TRIM
command will remove any spaces from the beginning and end of the username
field, returning the cleaned string as cleaned_username
. The output will be as follows:
username | cleaned_username |
---|---|
‘ john_doe ‘ | ‘john_doe’ |
‘ alice_123 ‘ | ‘alice_123’ |
‘ admin ‘ | ‘admin’ |
If a specific character needs to be removed, such as the hash symbol (#
), from both ends of the string, the following query can be used:
SELECT TRIM('#' FROM product_code) AS cleaned_product_codeFROM products;
This will remove any hash symbols (#
) from the beginning and end of each product_code
string. The output will be as follows:
product_code | cleaned_product_code |
---|---|
‘#AB123#’ | ‘AB123’ |
‘##XY456##’ | ‘XY456’ |
‘#LM789#’ | ‘LM789’ |
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn SQL on Codecademy
- Skill path
Analyze Data with SQL
Learn to analyze data with SQL and prepare for technical interviews.Includes 9 CoursesWith CertificateBeginner Friendly17 hours - Free course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner Friendly5 hours