In SQL Server, you can use the LEN()
function to return the number of characters in a string. This is a Transact-SQL function that can also be used in Azure databases.
In MySQL, you need to use the CHAR_LENGTH()
function.
Examples
Here’s an example of each.
SQL Server (T-SQL)
SELECT LEN('Cat') AS 'T-SQL';
Result:
T-SQL ----- 3
MySQL
SELECT CHAR_LENGTH('Cat') AS MySQL;
Result:
+-------+ | MySQL | +-------+ | 3 | +-------+
Watch Out for Trailing Blanks!
One difference between these functions is in the way they treat trailing blanks (e.g. spaces at the end of the string). T-SQL’s LEN()
function excludes trailing blanks, while MySQL’s CHAR_LENGTH()
function includes them.
So if we add trailing blanks to the previous examples, we get the following.
SQL Server (T-SQL)
SELECT LEN('Cat ') AS 'T-SQL';
Result:
T-SQL ----- 3
MySQL
SELECT CHAR_LENGTH('Cat ') AS MySQL;
Result:
+-------+ | MySQL | +-------+ | 4 | +-------+
If you need to exclude trailing blanks in MySQL, you’ll need to wrap the string in a TRIM()
function. Like this:
SELECT CHAR_LENGTH(TRIM('Cat ')) AS 'MySQL with TRIM';
Result:
+-----------------+ | MySQL with TRIM | +-----------------+ | 3 | +-----------------+
But Don’t Worry about Leading Blanks!
Both T-SQL’s LEN()
function and MySQL’s CHAR_LENGTH()
function include leading blanks.
SQL Server (T-SQL)
SELECT LEN(' Cat') AS 'T-SQL';
Result:
T-SQL ----- 4
MySQL
SELECT CHAR_LENGTH(' Cat') AS 'MySQL';
Result:
+-------+ | MySQL | +-------+ | 4 | +-------+