How to set NOT NULL to a column present in all the tables of my database at once?

58 Views Asked by At

I'm working with PostgreSQL. I have to set the NOT NULL property on a column that exists in all the tables of my database. I know how to set in one table, using:

ALTER TABLE table_name ALTER COLUMN column_name SET NOT NULL;

But I have about 400 tables in my database, so I need something to do it at once, does anybody the way?

Thank you in advance!

2

There are 2 best solutions below

0
Vivek S. On BEST ANSWER

As laurenz stated, you can achieve it by executing the ALTER commands in the DO statement like below,

DO $$
DECLARE
    selectrow record;
BEGIN
    FOR selectrow IN
        SELECT format(
                  'ALTER TABLE %I.%I ALTER %s SET NOT NULL;',
                  table_schema,
                  table_name,
                  'my_column'
               ) AS script
        FROM information_schema.tables
        WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
    LOOP
        EXECUTE selectrow.script
    END LOOP;
END;
$$;
0
Laurenz Albe On

Use psql's \gexec:

SELECT format(
          'ALTER TABLE %I.%I ALTER column_name SET NOT NULL;',
          table_schema,
          table_name
       )
FROM information_schema.tables
WHERE table_schema NOT IN ('pg_catalog', 'information_schema') \gexec

Alternatively, you can run the statement, save the output to a script and execute that.

You can also write a DO statement with PL/pgSQL code that loops through the results of the query and uses EXECUTE to execute them as dynamic SQL.