PostgreSQL Longest Record – How to Find the Longest Record for Each Column in PostgreSQL

postgispostgresqltable

I couldn't find the answer to this on here so sorry if repeated. I'm looking to query a table to find the longest record in characters for each column in a specific table.

I have a table which is built of fields which are type: varchar and length:254

In certain cases, I know for a fact that the longest record is a single character so the problem is when exporting to shapefiles the .dbf file is over 1gb when not needed.

If someone can also help with a script to reduce the lengths of each column as well that would be great!

Best Answer

The below worked for what I needed:

SELECT
        MAX(char_length(column1)) as column1,
        MAX(char_length(column2)) as column2
FROM
        schema.table
Related Question