There are a number of string functions in MySQL for extracting text, working out the position of a substring, calulating the length of text and so on. This post looks at how to work out the length of the longest string in a field in a MySQL table.
The LENGTH() function in MySQL returns the length of a string in bytes. Multi-byte characters will count as multiple bytes. The examples in this post will use the LENGTH() function but you can substitute them with the CHAR_LENGTH() function instead if you want to count the number of characters rather than bytes. Note that CHAR_LENGTH will treat a character that uses two bytes a one single character and would return 1.
This will return the number 14.
where "field_to_query" is the fieldname you want to query and table_to_query is the table. This will then return the length of the longest field named "field_to_query" as an integer.
This can be quite useful if you've loaded data from an external source into a table and want to ensure you have enough storage space for the data. I need to regularly load data from a text file into a MySQL table and one of the fields is labelled "long_description". Initially I created the field as a VARCHAR(255) and then ran the above query against the table only to discover the longest field(s) were 255 bytes long. I then changed the table to type TEXT and ran the query again and found out the longest field was acutally 1210 bytes long.