Using SQL LENGTH Function to Get String Length

Summary: in this tutorial, you will learn how to use the SQL LENGTH function to get the number of characters in a string.

Introduction to the SQL LENGTH  function

The SQL LENGTH function returns the number of characters in a string. The LENGTH function is available in every relational database systems. Some database systems use the LEN function that has the same effect as the LENGTH function.

The following illustrates the syntax of the LENGTH function.

LENGTH(string)Code language: SQL (Structured Query Language) (sql)

If the input string is empty, the LENGTH returns 0. It returns NULL if the input string is NULL.

The number of characters is the same as the number of bytes for the ASCII strings. For other character sets, they may be different.

The LENGTH function returns the number of bytes in some relational database systems such as MySQL and PostgreSQL. To get the number of characters in a string in MySQL and PostgreSQL, you use the CHAR_LENGTH function instead.

SQL LENGTH examples

The following statement uses the LENGTH function to return the number of characters the string SQL:

SELECT LENGTH('SQL');
Code language: SQL (Structured Query Language) (sql)
 length
--------
      3
(1 row)Code language: SQL (Structured Query Language) (sql)

See the following employees table in the sample database.
employees_table

The following statement returns the top five employees with the longest names.

SELECT 
    employee_id,
    CONCAT(first_name, ' ', last_name) AS full_name,
    LENGTH(CONCAT(first_name, ' ', last_name)) AS len
FROM
    employees
ORDER BY len DESC
LIMIT 5;Code language: SQL (Structured Query Language) (sql)
SQL LENGTH function example

How the query works.

  • First, use the CONCAT function to construct the full name of the employee by concatenating the first name, space, and last name.
  • Second, apply the LENGTH function to return the number of characters of the full name of each employee.
  • Third, sort the result set by the result of the LENGTH function and get five rows from the sorted result set.

In this tutorial, you have learned how to use the SQL LENGTH function to get the number of characters in a string.

Was this tutorial helpful ?