Question

How do I find the field with the longest length of a specific column in a MySQL table?

Was it helpful?

Solution 2

You can use the mysql command LENGTH()

<?php 
$q = mysql_query("SELECT LENGTH(yourfield) AS fieldlength FROM yourtable ORDER BY fieldlength DESC LIMIT 1"); 
echo $longestfield = mysql_result($q,0); 
?>

OTHER TIPS

MySQL has a lot of string functions you can use:

SELECT LENGTH(col) as my_len FROM my_table ORDER BY my_len DESC LIMIT 1

More funky version (it works):

SELECT MAX(LENGTH(col)) FROM my_table

You may wanna consider CHAR_LENGTH(). Differences from documentation:

CHAR_LENGTH(): Return number of characters in argument

LENGTH(): Return the length of a string in bytes

For example, when using UTF-8 on your column, these functions return different values.

And note that the length you set for a string column (ex: varchar) is actually its character length.

Let the name of the table be tbl1 and the name of the column be col1 in which you are trying to find the longest length value.

Approach 1:

select col1, length(col1) from tbl1 order by length(col1) desc limit 1

This will return the value and also the length of the value.

The above approach is best if their is only a single row or you want to retrieve only one row which is having the longest length. In case their are multiple rows which have longest length and you want to retrieve them all then the second Approach would be the best.

Approach 2:

select col1, length(col1) from tbl1 where length(col1) in (select max(length(col1)) from tbl1)

This will return both the value and also the length of the value of all the rows which is having the longest value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top