Is it possible to create a table with a variable name in PostgreSQL?

Using PL / pgSQL or (some other mechanism), is it possible to create a table with a variable name?

I would like to create several tables named table_1, table_2, table_3, etc .... and it would be easier if I could use a loop to create them instead of explicitly creating each of them.

I suspect that the answer is no, but I would like to confirm it.

+4
source share
2 answers

While I asked a question about your design, if you rely on such tricks, your question is general, and you did not provide specific information to judge in any case.

It should be possible, really. It is just a matter of programmatically creating table names as strings, and then loop through your CREATE statements as dynamic queries.

See this page in the postgres documentation: http://www.postgresql.org/docs/current/interactive/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN

+3
source

Create a script by building the commands dynamically in a loop, then run the resulting script.

0
source