SQL LEN Function | Return Length of String

LEN Function in SQL Server returns the length of the input string. It does not take the trailing spaces at the end of a string into account. However, it takes only the leading spaces in the starting of the string into account for calculating length. In this article, we will discuss the SQL LEN Function. Also, we will discuss a few examples of using it.

Syntax

LEN (string)

Parameters

The function expects only one parameter. You need to pass the string for which you want to calculate the length in the parameter.

Return Value

The LEN Function returns the length of the input string in SQL Server. Also, it takes into account only the leading spaces at the start of the string. However, it does not count the trailing spaces at the end.

Support

The function works in SQL Server (starting with 2008), Azure SQL Database, Azure SQL Data Warehouse, and Parallel Data Warehouse.

Examples

Let’s discuss a few examples of using the function in SQL Server.

Example 1: Calculate Length of String

SELECT LEN('concatly');

In the above example, the function returns the length of the string.in SQL Server.

+--------+
| length |
+--------+
|      8 |
+--------+

Example 2: Leading Spaces

For instance, consider an example where there are leading spaces in the starting of the string. The LEN Function in SQL Server counts those spaces as well.

SELECT LEN('concatly') no_spaces, LEN('   concatly') leading_spaces;
+-----------+----------------+
| no_spaces | leading_spaces |
+-----------+----------------+
|         8 |             11 |
+-----------+----------------+

Example 3: Trailing Spaces

However, the function does not count the spaces at the end of the string. Therefore, both the counts in the following query will be same in SQL Server.

mysql> SELECT LENGTH('concatly') as no_spaces, LENGTH('concatly   ') as trailing_spaces;
+-----------+-----------------+
| no_spaces | trailing_spaces |
+-----------+-----------------+
|         8 |              8 |
+-----------+-----------------+

Conclusion

In this article, we discussed the LEN Function in SQL Server. You can read more about it on the Microsoft Documentation. Additionally, you can also learn about SQL String Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *