Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql: Loop through each table and check for column?

I am trying to write a simple SQL query in pgAdmin to LOOP through each table in a database and change a specified column name IF it exists. I have never coded in SQL but after searching through many forums have managed to come up with:

DO
BEGIN
FOR i IN SELECT table_name FROM information_schema.tables
LOOP
   IF SELECT column_name FROM information_schema.columns WHERE table_name = 'i.table_name'
 THEN
   ALTER TABLE i.table_name RENAME COLUMN old_column_name TO new_column_name
END IF;
END LOOP;
like image 832
user3688391 Avatar asked Oct 17 '25 12:10

user3688391


1 Answers

You can skip information_schema.tables entirely. Just:

DO
$$
DECLARE
    rec record;
BEGIN
    FOR rec IN 
        SELECT table_schema, table_name, column_name
        FROM information_schema.columns 
        WHERE column_name = 'x'
    LOOP
        EXECUTE format('ALTER TABLE %I.%I RENAME COLUMN %I TO newname;',
            rec.table_schema, rec.table_name, rec.column_name);
    END LOOP;
END;
$$
LANGUAGE plpgsql;

with appropriate substitutions for 'x' and newname. Or make it into a function that takes them as parameters, whatever.

like image 126
Craig Ringer Avatar answered Oct 19 '25 01:10

Craig Ringer