Lessons › SQL › Deep Dive: Text, Date & Number Functions
SQL lesson
SUBSTRING() / LEFT() / RIGHT()
These functions slice out a specific portion of a text value - the beginning, the end, or any section in the middle.
Try this lesson free →Example
Extracting Retail Codes with SUBSTRING(), LEFT(), and RIGHT()
SELECT product_id,
LEFT(product_id, 4) AS category_code,
RIGHT(product_id, 5) AS item_number,
SUBSTRING(product_id, 6, 5) AS mid_section
FROM products| product_id | category_code | item_number | mid_section |
|---|---|---|---|
| ELEC-00142 | ELEC | 00142 | 00142 |
| CLTH-00389 | CLTH | 00389 | 00389 |
| HOME-00217 | HOME | 00217 | 00217 |
| BEAU-00056 | BEAU | 00056 | 00056 |
| SPRT-00901 | SPRT | 00901 | 00901 |
Step by step
- Run the query without SUBSTRING so you can see what the unfiltered values look like.
SELECT product_id, LEFT(product_id, 4) AS category_code, RIGHT(product_id, 5) AS item_number, product_id FROM products; - SUBSTRING pulls characters from text by position and length.
SELECT product_id, LEFT(product_id, 4) AS category_code, RIGHT(product_id, 5) AS item_number, SUBSTRING(product_id, 6, 5) FROM products; - AS gives the SUBSTRING result a friendly column name so the output reads cleanly.
SELECT product_id, LEFT(product_id, 4) AS category_code, RIGHT(product_id, 5) AS item_number, SUBSTRING(product_id, 6, 5) AS mid_section FROM products;
Practice
1. Using customers, write a query to show the first 2 characters of email.
SELECT LEFT(email, 2) FROM customers2. Using products, write a query to show the last 3 characters of product_id.
SELECT RIGHT(product_id, 3) FROM products3. Using suppliers, write a query to show the first 3 characters of supplier_id starting at position 1.
SELECT SUBSTRING(supplier_id, 1, 3) FROM suppliers4. Using employees, write a query to show the first 3 characters of employee_id.
SELECT LEFT(employee_id, 3) FROM employees5. Using reviews, write a query to show the last 2 characters of customer_id.
SELECT RIGHT(customer_id, 2) FROM reviewsLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →