Lessons › SQL › Deep Dive: Text, Date & Number Functions
SQL lesson
LENGTH() and CHAR_LENGTH() for text length
LENGTH() and CHAR_LENGTH() both measure how many characters are in a piece of text and return that count as a number. Like a ruler for words - drop any string on it and read off the exact length, so you can filter out anything too long or too short.
Try this lesson free →Example
Measuring how long text is
SELECT product_name, LENGTH(product_name) AS name_len FROM products| product_name | name_len |
|---|---|
| Wireless Earbuds | 16 |
| Ultra-Slim Stainless Steel Travel Mug | 37 |
| Cotton Tee | 10 |
| All-Season Performance Hiking Backpack 45L | 43 |
Step by step
- Run the query without LENGTH so you can see what the unfiltered values look like.
SELECT product_name, product_name FROM products; - LENGTH returns the number of characters in a string.
SELECT product_name, LENGTH(product_name) FROM products; - AS gives the LENGTH result a friendly column name so the output reads cleanly.
SELECT product_name, LENGTH(product_name) AS name_len FROM products;
Practice
1. Write a query on the customers table that returns the full_name column and a column called full_name_len with the number of characters in each full_name value.
SELECT full_name, LENGTH(full_name) AS full_name_len FROM customers2. Write a query on the products table that returns the category column and a column called category_len with the number of characters in each category value.
SELECT category, LENGTH(category) AS category_len FROM products3. Write a query on the suppliers table that returns the country column and a column called country_len with the number of characters in each country value.
SELECT country, LENGTH(country) AS country_len FROM suppliers4. Write a query on the employees table that returns the role column and a column called role_len with the number of characters in each role value.
SELECT role, LENGTH(role) AS role_len FROM employees5. Write a query on the reviews table that returns the product_id column and a column called product_id_len with the number of characters in each product_id value.
SELECT product_id, LENGTH(product_id) AS product_id_len 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 →