SELECT CustomerName, LENGTH(CustomerName) AS name_length
FROM Customers
WHERE LENGTH(CustomerName)>=20;
or
SELECT CustomerName, CHAR_LENGTH(CustomerName) AS name_length
FROM Customers
WHERE CHAR_LENGTH(CustomerName)>=20
Query will include the CustomerName and the corresponding name_length for those customers whose names have a length of 20 characters or more
Definitions:
LENGTH(): returns the length of a string (in bytes).
CHAR_LENGTH(): return the length of a string (in characters).
Important Note:
Using Length() indeed passes all the test cases in this example. But it fails in case of UTF8 where different characters take up different number of bytes.
For example: Each Chinese character is represented by 3 bytes.
-- Creating a table with a string containing a multibyte character
CREATE TABLE Example (
id INT,
content VARCHAR(50)
);
INSERT INTO Example VALUES
(1, 'Hello, 你好'); --> ('Hello' -> 3 + ', ' -> 4 + '你好' -> 6 = 13)
SELECT LENGTH(content) AS Char_Length FROM Example;
Correct length of the string is 9 but using Length() here gives out 13 as the answer.
or
Query will include the
CustomerName
and the correspondingname_length
for those customers whose names have a length of 20 characters or moreDefinitions:
Important Note: Using Length() indeed passes all the test cases in this example. But it fails in case of UTF8 where different characters take up different number of bytes.
For example: Each Chinese character is represented by 3 bytes.
Correct length of the string is 9 but using Length() here gives out 13 as the answer.