Averages and SQL Functions

What is length() in SQL?

Learn what length() does in SQL, how MySQL, PostgreSQL and SQL Server count characters versus bytes, and how to average string lengths per group.

On this page
  1. The short answer
  2. Using it in a query
  3. Spaces count
  4. Averaging string lengths

The short answer

length() returns the number of characters in a text value. Which function you call, and whether it counts characters or bytes, depends on the database.

Database Function Counts
PostgreSQL length() or char_length() characters
SQLite length() characters, for text values
MySQL CHAR_LENGTH() characters
MySQL LENGTH() bytes
SQL Server LEN() characters, not counting trailing spaces
SQL Server DATALENGTH() bytes

SQL Server has no function named length(). MySQL is the one to watch for bytes. A character can take more than one byte, and the MySQL manual’s example uses two characters that each take three bytes: LENGTH() returns 6 for that string, and CHAR_LENGTH() returns 2.

Using it in a query

-- PostgreSQL and SQLite
SELECT product_name, length(product_name) AS name_length
FROM products;

-- MySQL
SELECT product_name, CHAR_LENGTH(product_name) AS name_length
FROM products;

-- SQL Server
SELECT product_name, LEN(product_name) AS name_length
FROM products;

Spaces count

Spaces are characters too. In PostgreSQL, length(' hi ') returns 6. In SQL Server, LEN(' hi ') returns 4, because LEN ignores trailing spaces but still counts leading ones.

If the spaces should not count, trim them before you measure. Many people ask what does trim() do in SQL right at this step. By default, TRIM() removes spaces from both ends of a value:

SELECT product_name, length(TRIM(product_name)) AS name_length
FROM products;

Averaging string lengths

Put length() inside AVG() to find the average length for each group:

SELECT category, AVG(CHAR_LENGTH(product_name)) AS avg_name_length
FROM products
GROUP BY category;

In PostgreSQL or SQLite, swap in length(). The same AVG() and GROUP BY pattern appears in how to calculate average for each row in SQL.

In SQL Server, LEN() returns an integer, and AVG() of an integer returns an integer too, so the decimal part is dropped. Cast the value first:

SELECT category, AVG(CAST(LEN(product_name) AS DECIMAL(10, 2))) AS avg_name_length
FROM products
GROUP BY category;

The complete guide to averages and sql functions

How to Calculate the Average for Each Row in SQL
Read the guide

Keep exploring

Guides from other topics

All topics →