LENGTH (SQL)

Returns the number of characters in a character string or the number of bytes in a binary string.

Syntax

LENGTH ( expression )

Parameters

Return Type

Returns an integer. For character strings, it returns the number of characters. For binary strings, it returns the number of bytes.

Remarks

The LENGTH function counts characters or bytes, not multibyte characters. For example, if a character string contains a double-byte character, it still counts as one character.

If the input string is NULL, LENGTH returns NULL.

Examples

Example 1: Using LENGTH with a character string

This example returns the length of the string 'Hello, SQL!'.


SELECT LENGTH('Hello, SQL!');
-- Returns: 12
                

Example 2: Using LENGTH with a column

This example returns the length of each product name from the Products table.


SELECT ProductName, LENGTH(ProductName) AS ProductLength
FROM Products;
                

Example 3: Using LENGTH with a variable

This example demonstrates using LENGTH with a declared variable.


DECLARE @myString VARCHAR(50) = 'Microsoft';
SELECT LENGTH(@myString);
-- Returns: 9
                

Example 4: Using LENGTH with a NULL value

This example shows how LENGTH handles NULL input.


SELECT LENGTH(NULL);
-- Returns: NULL
                

See Also