PostgreSQL – How to ALTER All Columns of One Type to Another

alter-tabledatatypespostgresql

Let's say I want to change the data type of all columns of one type to another. How would I go about doing this, for example converting all bigints to ints.

Best Answer

In psql, you'd run something like this which will output a bunch of commands.

SELECT format(
  'ALTER TABLE %I.%I.%I ALTER COLUMN %I SET DATA TYPE int;',
  table_catalog,
  table_schema,
  table_name,
  column_name
)
FROM information_schema.columns
WHERE data_type = 'bigint'
  AND table_schema NOT LIKE 'pg_%'
  AND lower(table_schema) <> 'information_schema'
  AND is_updatable = 'YES';

You can spot check them and if you're good to go execute them with \gexec.