T-SQL Tutorial

Get length of string


In SQL Server, the length of a string, also known as the character count or the number of characters in a text value, can be determined using various methods. The length of a string is an important concept in database management and is frequently used in SQL queries for data manipulation, validation, and reporting.

Here are some common methods to calculate the length of a string in SQL Server:


LEN() Function

The most straightforward way to get the length of a string in SQL Server is by using the LEN() function. You can use it like this:

SELECT LEN('Hello, World!') AS StringLength;

The result of this query will be 13, which is the number of characters in the string 'Hello, World!'.


DATALENGTH() Function

The DATALENGTH() function returns the number of bytes used to represent a string. In most cases, each character in a string is represented using one byte in SQL Server, but this can vary if you are using Unicode or non-Unicode character encodings.

SELECT DATALENGTH('Hello, World!') AS DataLength;

The result will be 13, the same as the LEN() function for this example.


Using the LEN() Function with Columns

You can also use the LEN() function with columns from database tables. For instance, if you have a table called Products with a column named ProductName, you can find the lengths of the product names for all records using a query like this:

SELECT
ProductName, LEN(ProductName) AS NameLength
FROM Products;


Using LEN() and RTRIM() to Calculate Trimmed Length

If you want to calculate the length of a string after trimming leading and trailing spaces, you can use the RTRIM() function along with LEN(). This is useful for ensuring that a string does not contain unnecessary whitespace.

SELECT LEN(RTRIM(' Example String ')) AS TrimmedLength;

The result will be 13, which is the length of the string after removing leading and trailing spaces.


The method you choose for calculating the length of a string in SQL Server depends on your specific use case and the character encoding you are working with. Whether you're dealing with standard ASCII characters or more complex character sets, SQL Server provides various functions to help you determine the length of strings accurately.