LENGTH()/LEN() in SQL
Returns the number of characters in a string. Note: Function name varies by DBMS (LENGTH in most, LEN in SQL Server).
Syntax
Return type
LENGTH()/LEN() Function Example
What is LENGTH()/LEN() in SQL?
The LENGTH()
(or LEN()
in SQL Server) function in SQL returns the number of characters in a given string, including spaces. It is commonly used to validate text length, filter data based on string size, and optimize storage by ensuring text fields adhere to expected constraints. This function is supported across various SQL databases, with LENGTH()
used in MySQL, PostgreSQL, and SQLite, while LEN()
is specific to SQL Server. The function counts each character, including whitespace, and is frequently applied in text analysis, data validation, and string manipulation tasks.
Parameters:
string: The input string whose length is to be measured
Example Use Cases:
-- Validate password length
-- Find longest product names
-- Filter short descriptions
Notes:
Behavior: Most DBMSs count all characters including spaces, but SQL Server's LEN() excludes trailing spaces, and Unicode character handling varies across DBMSs.
Performance Considerations: Very efficient, commonly used in indexes
Version Info: Core SQL function, available in all major versions
Error Handling:
Error: Returns NULL for NULL input
Supported Databases:
DBMS
Function / Syntax
Example
Behavior with NULL
MySQL
LENGTH()
LENGTH('Hello')
Returns NULL
PostgreSQL
LENGTH()
LENGTH('Hello')
Returns NULL
SQL Server
LEN()
LEN('Hello')
Returns NULL
SQLite
LENGTH()
LENGTH('Hello')
Returns NULL
BigQuery
LENGTH()
LENGTH('Hello')
Returns NULL
Snowflake
LENGTH()
LENGTH('Hello')
Returns NULL
Athena
LENGTH()
LENGTH('Hello')
Returns NULL