title: Alter table add column default and execute the default for each row
body: <p>I am making a function that adds a id column to a given table, creates a sequence and fills the new columns value. The thing is that the column is created but now I need to fill it with <code>nextval()</code> of the created sequence (1,2,3,4,5...). I don't know how to specify that in the add column sentence.</p>
  
  <pre><code>CREATE OR REPLACE FUNCTION create_id(tabla character varying)
    RETURNS void AS
  $BODY$ 
  DECLARE
  
  BEGIN
  
  IF NOT EXISTS (SELECT information_schema.columns.column_name FROM information_schema.columns WHERE information_schema.columns.table_name=tabla AND information_schema.columns.column_name='id')
  THEN
      EXECUTE 'ALTER TABLE '|| tabla ||' ADD COLUMN id numeric(8,0)';
  
      IF NOT EXISTS (SELECT relname FROM pg_class WHERE relname='seq_id_'||tabla) 
      THEN
          EXECUTE 'CREATE SEQUENCE seq_id_'||tabla||' INCREMENT 1  MINVALUE 1  MAXVALUE 9223372036854775807  START 1 CACHE 1';
          EXECUTE 'GRANT ALL ON TABLE seq_id_'||tabla||' TO postgres';
          EXECUTE 'ALTER TABLE ONLY '||tabla||' ALTER COLUMN id SET DEFAULT nextval(''seq_id_'||tabla||'''::regclass)';
      END IF; 
  END IF;
  
  RETURN;
  END;
  $BODY$
    LANGUAGE plpgsql;
  </code></pre>