Jacobvu84 / sql-basic-advance

SQL
0 stars 0 forks source link

Count the length of string #1

Open Jacobvu84 opened 6 months ago

Jacobvu84 commented 6 months ago
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:

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.