1

I can do the following in MySQL, but would like to know how to do the equivalent in PostgreSQL. I have to wrap the query in a string because the table name is variable (can't just run CREATE TABLE). This is all in a MySQL stored procedure / Postgres function.

    SET @createTable = CONCAT("CREATE TABLE ", table_name, "(
              id int(11) NOT NULL AUTO_INCREMENT,
              something varchar(255) NOT NULL");
    PREPARE createTableStmt FROM @createTable;
    EXECUTE createTableStmt;
    DEALLOCATE PREPARE createTableStmt;

Can someone please tell me how to do this in Postgres?

1

1 Answer 1

2

To run it once, just run the concatenated CREATE TABLE statement.

To encapsulate the functionality for repeated use with variable table name, use a plpgsql function with EXECUTE:

CREATE OR REPLACE FUNCTION create_my_table(_tbl text)
  RETURNS void AS
$func$
BEGIN
   EXECUTE format('CREATE TABLE %I (id serial, something varchar(255) NOT NULL)', _tbl);
END
$func$ LANGUAGE plpgsql;

Call:

SELECT create_my_table('foo_table');

To drop:

DROP create_my_table(text);

There are many related answers here. Try a search.

Or if you only need it for the current session you can make it a temporary function that is dropped at the end of the session automatically:

CREATE OR REPLACE FUNCTION pg_temp.create_my_table(_tbl text) ...

Use a serial column to implement AUTOINCREMENT in Postgres:

You might want to make the column PRIMARY KEY as well.
And varchar(255) rarely makes sense. I would just use text instead:

Sign up to request clarification or add additional context in comments.

1 Comment

You're awesome! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.