Alright, you know at Dataford, we all about use cases and practice! So let's go over these concepts that will again be so useful when manipulating text data!
LEFT is a function used to extract a specified number of characters from the left side of a string. The RIGHT function does it from the right side of a string.
Let's say, you have the users table with 3 columns (user_id, name and zip code):
| user_id | name | zip_code |
|---|---|---|
| 1 | Alice | 1234-56 |
| 2 | Bob | 2345-67 |
| 3 | Charlie | 3456-78 |
You only want to extract the first 4 digits of the zip code. We will use the LEFT function and specify the number of characters we want to extract on the left side. This is how it looks in SQL:
SELECT
LEFT(zip_code, 4) AS new_zip_code
FROM users
With that query, you will be able to get the new zip code for each user:
| user_id | name | new_zip_code |
|---|---|---|
| 1 | Alice | 1234 |
| 2 | Bob | 2345 |
| 3 | Charlie | 3456 |
Now, we will be adding a new column to our users table called Social Security Number. We only want to extract the last 4 digits (yes, that one they ask you all the time).
| user_id | name | zip_code | ssn_number |
|---|---|---|---|
| 1 | Alice | 1234-56 | 123-45-6789 |
| 2 | Bob | 2345-67 | 234-56-7890 |
| 3 | Charlie | 3456-78 | 345-67-8901 |
If we want to extract the last 4 digits, we will use the RIGHT function and specify the number of characters we want to extract.
SELECT
RIGHT(ssn_number, 4) AS last_4_digits
FROM users
Using the same users table, we want to know the number of characters for each name. For that, we will use the LENGTH function.
SELECT
LENGTH(name) AS name_length
FROM users
Know you got to use 3 new concepts: LEFT, RIGHT and LENGTH, and now let's practice!
