Postgresql – Altering Tables using Tablenames from other Table

alter-databasealter-tablepostgresql

I have a database with several tables and i have a table which contains all tablenames which I want to alter.

I want to perform a query like this:

ALTER TABLE (SELECT "TABLE_NAME" FROM "RESOURCE_TABLES)  DROP COLUMN ID;

My Table RESOURCE_TABLE with Table Names:

TABLE_NAME     ID  

Table1          1            
Table2          2
Table3          3
  ...          ...

How can I alter all tables named in the table in the column TABLE_NAME with a loop or a query?

So i want Table1,Table2,Table3 to drop a column id without executing a single alter table query on each table because maybe the tables are 100 Tables.

Best Answer

You can loop using an EXECUTE statement. I believe this post has the exact answer you're looking for, you just need to change the ALTER statement.