SQL Server LEN() Function

The SQL Server LEN() function is used to return the length (number of characters) of a string expression. The string expression can be a character or string field, variable, or literal.

Syntax

LEN(string_expression)

Parameters:

  • string_expression: Required. The string or character expression for which to calculate the length.

Usage

The LEN() function is useful when working with strings. It can be used to obtain the length of a string, allowing you to filter, compare, or display strings in a query.

Some common use cases include:

  • Obtaining the length of a string.
  • Filtering, comparing, or displaying strings in a query.

Examples

Example 1

Use the LEN() function to obtain the length of a string.

SELECT LEN('Hello World') AS StringLength;

Result:

StringLength
11

Example 2

Use the LEN() function to obtain the length of a column value.

Assume we have a table named employees that contains columns first_name and last_name. You can use the LEN() function to obtain the length of each name.

SELECT first_name,
  last_name,
  LEN(first_name) AS first_name_length,
  LEN(last_name) AS last_name_length
FROM employees;

Result:

first_name last_name first_name_length last_name_length
John Smith 4 5
Sarah Johnson 5 7

Conclusion

The LEN() function is a very useful function that can be used in queries to obtain the length of a string. It can be used to obtain the length of any string, whether it is a string constant, variable, or expression. In some cases, using the LEN() function can make your queries more concise and readable.