BBampaa

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 →
About 5–10 minutes · no sign-up needed

Example

Measuring how long text is

SELECT product_name, LENGTH(product_name) AS name_len FROM products

Result:

product_namename_len
Wireless Earbuds16
Ultra-Slim Stainless Steel Travel Mug37
Cotton Tee10
All-Season Performance Hiking Backpack 45L43

Step by step

  1. Run the query without LENGTH so you can see what the unfiltered values look like.
    SELECT product_name, product_name FROM products;
  2. LENGTH returns the number of characters in a string.
    SELECT product_name, LENGTH(product_name) FROM products;
  3. 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

Try each one in your head first, then open the answer.

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 customers
2. 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 products
3. 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 suppliers
4. 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 employees
5. 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 reviews

Learn 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 →
About 5–10 minutes · no sign-up needed