Returns the number of characters in a character string or the number of bytes in a binary string.
LENGTH ( expression )
Returns an integer. For character strings, it returns the number of characters. For binary strings, it returns the number of bytes.
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.
This example returns the length of the string 'Hello, SQL!'.
SELECT LENGTH('Hello, SQL!');
-- Returns: 12
This example returns the length of each product name from the Products table.
SELECT ProductName, LENGTH(ProductName) AS ProductLength
FROM Products;
This example demonstrates using LENGTH with a declared variable.
DECLARE @myString VARCHAR(50) = 'Microsoft';
SELECT LENGTH(@myString);
-- Returns: 9
This example shows how LENGTH handles NULL input.
SELECT LENGTH(NULL);
-- Returns: NULL