LEN Function in MS SQL Server and Its Counterpart in MySQL


LEN in MSSQL returns the length of a given string, and MySQL's LENGTH function achieves the same result — but there's a catch. LEN in MSSQL excludes trailing blank spaces; MySQL's LENGTH includes them.

In MSSQL there's another function, DATALENGTH, which returns the number of characters in a string without excluding trailing blank spaces.

MSSQL Examples

select len('demo ')
-----------------------
4

select datalength('demo  ')
------------------------
6

LEN and DATALENGTH function in MSSQL

MySQL

In MySQL, the LENGTH function has the same core purpose but doesn't trim trailing blank spaces. It returns the length of the string in bytes, so it isn't suitable for unicode strings, which are multi-byte. Use CHAR_LENGTH to count the number of characters regardless of whether they're single-byte or multi-byte.

Examples:

mysql> select length('demo   ');
+-------------------+
| length('demo   ') |
+-------------------+
| 7                 |
+-------------------+

mysql> select char_length('demo ');
+------------------------+
| char_length('demo ')   |
+------------------------+
| 7                      |
+------------------------+

LENGTH Function in MySQL

Comparison of LENGTH and CHAR_LENGTH for unicode strings:

LENGTH and CHAR_LENGTH function in MySQL

Back to Converting Functions from MSSQL to MySQL