title: Using a variable in a Postgres function
body: <p>I'm sure someone has asked this question before but I wasn't able to find it by searching around. So at least if it gets marked as a duplicate, maybe it'll be easier to find here. The Postgres docs have not helped me.</p>
  
  <p>I have the following SQL:</p>
  
  <pre><code>create table foobar(col1 bool);
  create or replace function foo(tablename varchar) returns void as $func$
  begin
    alter table tablename add column if not exists bar boolean;
  end;
  $func$ language plpgsql;
  select foo('foobar');
  </code></pre>
  
  <p>What I expect to happen:</p>
  
  <ul>
  <li>Create a table foobar with boolean column col1</li>
  <li>Create a function foo which adds a boolean column bar to specified table</li>
  <li>Run function to add this column to table foobar</li>
  </ul>
  
  <p>What actually happens, is that the first two SQL statements are executed successfully but the third fails:</p>
  
  <blockquote>
    <p>ERROR: relation "tablename" does not exist</p>
  </blockquote>
  
  <p>My IDE is telling me that this should be fine. I have fussed with this for a while and have not been able to come up with a way to make this cooperate except by using format() string replacement:</p>
  
  <pre><code>create or replace function foo(tablename varchar) returns void as $func$
  begin
    execute(format('alter table %I add column if not exists bar boolean;', tablename));
  end;
  $func$ language plpgsql;
  </code></pre>
  
  <p>Is there really no other way of doing this?</p>