create function user_news_new(text) returns void as $$ declare name text; cat_name alias for $1; begin CREATE TEMPORARY TABLE temptest(category_id INTEGER,category_name text); for name in select label_name from category_labels where category_id = (select category_id from category where category_name=cat_name) loop execute 'alter table temptest add column ' || name || ' text'; end loop; select * from user_news where category_id= end; $$ language plpgsql; /* category_label table contains all the field_name entries of category_id's */