Search code examples
sqlitemaxaggregate-functions

I want to find max lenght of string from a tabe in SQLite


SELECT MAX(SELECT MAX(LENGTH(`name`)) count FROM `student_info` 
UNION SELECT MAX(LENGTH(`address`)) count FROM `student_info` 
UNION SELECT MAX(LENGTH(`class`)) count FROM `student_info` 
UNION SELECT MAX(LENGTH(`roll`)) count FROM `student_info` 
UNION SELECT MAX(LENGTH(`subject`)) count FROM `student_info`) 
FROM `student_info`

by using similar type of query i want to find one max value of string so i can manage table properly.

what is the proper query for SQLite?


Solution

  • There is no need for UNION.

    Get each column's max length with MAX() aggregate function and then use MAX() scalar function to get the greatest of all:

    SELECT MAX(
             MAX(LENGTH(name)),
             MAX(LENGTH(address)), 
             MAX(LENGTH(class)), 
             MAX(LENGTH(roll)), 
             MAX(LENGTH(subject))
           ) AS max_count 
    FROM student_info;
    

    Or:

    SELECT MAX(
             MAX(
               LENGTH(name),
               LENGTH(address), 
               LENGTH(class), 
               LENGTH(roll), 
               LENGTH(subject)
             )
           ) AS max_count 
    FROM student_info;
    

    See a simplified demo.