How to find the maximum length of data in a particular field in postgresql?

Another option:

select username, length(username) as username_length
from users
where length(username) = (select max(length(username)) from users)

This would return multiple users in case there be a tie for the longest username. If you have specific rules for breaking a tie then update your question.


another possability to avoid mass-use of functions:

SELECT
     username
   , length(username)
FROM
    users
GROUP BY
    username
ORDER BY
    length(username) desc
LIMIT 1;

You will have use a subquery because the group by will prevent desired results if you were to use a HAVING clause

SELECT name, LENGTH(name)
FROM your_table
WHERE LENGTH(name)=( SELECT MAX(length(name)) FROM your_table)
GROUP BY name

additionally you can test the answer on this sqlfiddler http://sqlfiddle.com/#!15/c0ff8/5

Tags:

Postgresql