I need to alter the Data Type of a named column (let’s call them ‘photo’) across all the tables in a schema.
For example: I have 300 tables with identical structure (except the data in each row of course).
But I have to change the varchar(255) in the photo column to (500) on every table.
Is there a way to do it without going through every table and doing it manually?
I tried everything I found on the internet. Used ChatGPT (useless as always) but to no avail.
2
Answers
An example, obviously not tested on your instance, so try out on test database first. In
psql
do:Change the
relnamespace
value to the schema you are looking to change the tables in.This query on
information_schema
shows both the list of all tables with the column to be altered and in the last column theALTER
statement to perform the change.Adjust the schema/column name as required.
Sample output
Note that to
format
theALTER
statement theI
type is used, to avoid problems with mixed case names and SQL injection as commented.I recommend for this ad hoc task a two step strategy:
ALTER TABLE jdbn."Table2" ALTER COLUMN photo TYPE text;
ALTER TABLE jdbn."harmless; but here is something evil" ALTER COLUMN photo TYPE text;
ALTER TABLE jdbn.t1 ALTER COLUMN photo TYPE text;
commit
if OK.