I have a string that contains 253 characters, but takes up 261 bytes due to some of the characters being longer than one byte (in this case, it contains several zero-width spaces).
I want to insert this string into a VARCHAR(255)
column in a utf8mb4
table, but it throws this error:
INSERT INTO mytable(mycolumn) VALUES("This string contains 253 characters which should fit inside of a varchar(255) column, but because of the zero width spaces, it takes up more than 255 bytes and therefore throws an error when you try to insert it into the table and that makes me sad.")
/*Error 1406: Data too long for column*/
Here's an example of what the two length functions output:
/* Returns 253 */
SELECT CHAR_LENGTH("This string contains 253 characters which should fit inside of a varchar(255) column, but because of the zero width spaces, it takes up more than 255 bytes and therefore throws an error when you try to insert it into the table and that makes me sad.");
/* Returns 261 */
SELECT LENGTH("This string contains 253 characters which should fit inside of a varchar(255) column, but because of the zero width spaces, it takes up more than 255 bytes and therefore throws an error when you try to insert it into the table and that makes me sad.");
To fix that, I need to trim off just enough characters for the string to be within the byte limit.
Unfortunately, the LEFT()
function doesn't appear to be suitable for this:
/* Still returns 261 because it counts characters, not bytes */
SELECT LENGTH(LEFT("This string contains 253 characters which should fit inside of a varchar(255) column, but because of the zero width spaces, it takes up more than 255 bytes and therefore throws an error when you try to insert it into the table and that makes me sad.", 255));
So, how can I trim the string down?