How to determine which column is implicated in "value too long for type character varying"?

Stephen Lead picture Stephen Lead · Apr 8, 2016 · Viewed 7.3k times · Source

I'm programatically adding data to a PostgreSQL table using Python and psycopg - this is working fine.

Occasionally though, a text value is too long for the containing column, so I get the message:

ERROR: value too long for type character varying(1000)

where the number is the width of the offending column.

Is there a way to determine which column has caused the error? (Aside from comparing each column's length to see whether it is 1000)

Answer

Stephen Lead picture Stephen Lead · Apr 11, 2016

Many thanks to @Tometzky, whose comment pointed me in the right direction.

Rather than trying to determine which column caused the problem after the fact, I modified my Python script to ensure that the value was truncated before inserting into the database.

  1. access the table's schema using select column_name, data_type, character_maximum_length from information_schema.columns where table_name='test'

  2. when building the INSERT statement, use the schema definition to identify character fields and truncate if necessary