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!
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;
$$;