How to Trim Strings in SQL

Whether you're trying to remove whitespace from the beginning or end of a string, or you're trying to remove a specific character from the middle of a string, the solution is to use the TRIM() function in SQL. This function takes two arguments: a character or characters to trim, and an optional direction (either LEADING, TRAILING, or BOTH). If the direction is not specified, it defaults to BOTH. For example, if you wanted to trim whitespace from the beginning and end of a string, you would use the following query:

SELECT TRIM(string_column) FROM table_name;

Examples

Let's look at a few examples of how this function can be used. Suppose you have a table called users with the following data:

users
nameage
John25
Jane30
John25
Bob20


If you wanted to trim whitespace from the beginning and end of the name column, you would use the following query:

SELECT TRIM(name) FROM users;

This query would return the result John, Jane, John, and Bob. Note that the whitespace has been trimmed from the beginning and end of each name.

Additional Info

The TRIM() function is supported by most major databases, including MySQL, PostgreSQL, and SQL Server. However, the syntax may vary slightly depending on the database you are using. For more information, check out the documentation for your particular database.

Want to build your own LLM Apps with AirOps👇👇