Skip to content

sql_func_len

Most SQL databases provide a function to determine the length of a string (the number of characters in a text value). This is commonly used for data validation, analysis, or formatting.

The standard SQL function name is CHAR_LENGTH() or CHARACTER_LENGTH(). Many systems also offer LENGTH() or LEN().

MySQL, PostgreSQL, Oracle: LENGTH(string) or CHAR_LENGTH(string)

SELECT LENGTH(column_name) FROM table_name;
SELECT CHAR_LENGTH(column_name) FROM table_name;

Note: For some databases and character sets (especially multi-byte like UTF-8), LENGTH() might return the length in bytes, while CHAR_LENGTH() returns the number of characters. It’s usually safer to use CHAR_LENGTH() if you specifically need the character count.

SQL Server: LEN(string)

SELECT LEN(column_name) FROM table_name;

Note: SQL Server’s LEN() function historically excludes trailing spaces. To include trailing spaces in the count, you might need to use DATALENGTH() for byte count or combine LEN() with other functions if character count including trailing spaces is critical.

For these examples, let’s use a Customers table that includes an Address column and a CustomerName column, both storing text data.

Example (MySQL, PostgreSQL, Oracle using LENGTH or CHAR_LENGTH):

Section titled “Example (MySQL, PostgreSQL, Oracle using LENGTH or CHAR_LENGTH):”

The following SQL statement selects the CustomerName and the length of the Address string for each customer. The result column is aliased as AddressLength.

SELECT CustomerName, CHAR_LENGTH(Address) AS AddressLength
FROM Customers;

The following SQL statement selects the CustomerName and the length of the Address string. The result column is aliased as AddressLength.

SELECT CustomerName, LEN(Address) AS AddressLength
FROM Customers;

Data Validation: Ensure a username or password meets minimum/maximum length requirements.

Data Cleaning: Identify unexpectedly short or long strings that might indicate data entry errors.

Analysis: Calculate average lengths of comments or descriptions.

Resource Link: For specific behavior regarding multi-byte characters or trailing spaces, always consult the documentation for your particular database system (e.g., search for ‘MySQL LENGTH function’ or ‘SQL Server LEN function’).