title: PostgreSQL dynamic column selection
body: <p>I am struggling a bit on some dynamic postgresql :
  I have a table named &quot;list_columns&quot; containing the columns names list with &quot;column_name&quot; as the variable name; those column names come from an input table called &quot;input_table&quot;.</p>
  <p><strong>[list_columns]</strong></p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th><strong>column_name</strong></th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td><em>col_name_a</em></td>
  </tr>
  <tr>
  <td><em>col_name_b</em></td>
  </tr>
  <tr>
  <td><em>col_name_c...</em></td>
  </tr>
  </tbody>
  </table>
  </div><hr />
  <p><strong>[input_table]</strong></p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th><strong>col_name_a</strong></th>
  <th><strong>col_name_b</strong></th>
  <th><strong>col_name_c</strong></th>
  <th><strong>col_name_d</strong></th>
  <th><strong>col_name_e</strong></th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>value_a_1</td>
  <td>value_b_1</td>
  <td>value_c_1</td>
  <td>value_d_1</td>
  <td>value_e_1</td>
  </tr>
  <tr>
  <td>value_a_2</td>
  <td>value_b_2</td>
  <td>value_c_2</td>
  <td>value_d_2</td>
  <td>value_e_2</td>
  </tr>
  <tr>
  <td>...</td>
  <td>...</td>
  <td>...</td>
  <td>...</td>
  <td>...</td>
  </tr>
  </tbody>
  </table>
  </div><hr />
  <p>What I'd like to do is dynamically create a new table using that list, something like this:</p>
  <pre><code>create table output_table as
  select (select distinct(column_name) seperated by &quot;,&quot; from list_columns) from input_table;
  </code></pre>
  <p>The resulting table would be
  <strong>[output_table]</strong></p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th><strong>col_name_a</strong></th>
  <th><strong>col_name_b</strong></th>
  <th><strong>col_name_c</strong></th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>value_a_1</td>
  <td>value_b_1</td>
  <td>value_c_1</td>
  </tr>
  <tr>
  <td>value_a_2</td>
  <td>value_b_2</td>
  <td>value_c_2</td>
  </tr>
  <tr>
  <td>...</td>
  <td>...</td>
  <td>...</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p>I saw I should use some execute procedures but I can't figure out how to do so.</p>
  <p><em>Note: I know i could directly select the 3 columns; I oversimplied the case.</em></p>
  <p>If someone would be kind enough to help me on this,</p>
  <p>Thank you,
  Regards,
  Jonathan</p>