TRIM is a function used to remove leading and trailing spaces from a string. In many companies, there are some data entry error that can occurs, causing customer names to have extra spaces, which could cause issue in data processing.
As Gordon Ramsay says:
<img src="https://storage.googleapis.com/dataford-assets/learning-path/trim_the_fat.gif" width="384px" height="216px" />
That's why you need to know about it!
Let's use a specific example. Imagine working at Amazon with a table called customers which stores the customer_id and their names:
| customer_id | customer_name |
|---|---|
| 1 | ' Alice Walker ' |
| 2 | 'Bob Smith' |
| 3 | ' Charles ' |
| 4 | ' Diana Ross' |
| 5 | 'Elaine ' |
By the way, I am using quote here to show you that in this table, the customer_name column has names with inconsistent spacing. To remove this spacing you will the TRIM function:
SELECT
customer_id,
customer_name,
TRIM(customer_name) AS cleaned_name
FROM customers;
After using the TRIM function, we were able to remove all the spacing to have a clean name:
| customer_id | customer_name | Cleaned_Name |
|---|---|---|
| 1 | ' Alice Walker ' | 'Alice Walker' |
| 2 | 'Bob Smith' | 'Bob Smith' |
| 3 | ' Charles ' | 'Charles' |
| 4 | ' Diana Ross' | 'Diana Ross' |
| 5 | 'Elaine ' | 'Elaine' |
By the way, something cool to know. If you only want to remove space at the beginning or at the end, you can actually specify it in your TRIM function:
SELECT
customer_id,
customer_name,
TRIM(LEADING FROM customer_name) AS removing_space_beginning,
TRIM(TRAILING FROM customer_name) AS removing_space_at_the_end
FROM
customers;
By specifying LEADING you will only remove spaces at the beginning of the string. And with TRAILING at the end of the STRING.
Cool, let's go through some round of practice now! 🙇♂️