Postgresql – procedure for postgres to create table if not exist

informaticapostgresql

i want to create table if that doesn't, i tried below code:

create or replace function create_table() returns void as
$$
begin
    if not exists(select * 
                  from   pg_tables 
                  where  schemaname = 'Public'
                  and    tablename = 'test') 
    then

        create table test
        (
            the_id int not null,
            name text
        );

    end if;

end;
$$
language 'plpgsql';

While executing this procedure first time:

select creat_table();

table gets created but when I execute it again I get the below error:

ERROR:  relation "test" already exists
CONTEXT:  SQL statement "create table test
        (
            the_id int not null,
            name text
        )"
PL/pgSQL function create_table() line 8 at SQL statement
********** Error **********

ERROR: relation "test" already exists
SQL state: 42P07
Context: SQL statement "create table test
        (
            the_id int not null,
            name text
        )"
PL/pgSQL function create_table() line 8 at SQL statement

How to achieve this, and also I want to call this procedure from Informatica pre-sql target session property so i want to call procedure with table name as parameter.

Best Answer

Just use CREATE TABLE [IF NOT EXISTS]

Looks like this,

CREATE TABLE IF NOT EXISTS test (
  the_id  int   PRIMARY KEY,
  name    text
);

If you must wrap it in a function (don't though, there is no point),

CREATE FUNCTION myCreateTable() RETURNS void AS $$
  CREATE TABLE IF NOT EXISTS test (
    the_id  int   PRIMARY KEY,
    name    text
  );
$$ LANGUAGE sql
VOLATILE;

If you want that function to accept a name (still wouldn't suggest this),

CREATE OR REPLACE FUNCTION myCreateTable(myIdent text) RETURNS void AS $$
  BEGIN
    EXECUTE format(
      '
        CREATE TABLE IF NOT EXISTS %I (
          the_id  int   PRIMARY KEY,
          name    text
        );
      ',
      myIdent
    );
  END;
$$ LANGUAGE plpgsql
VOLATILE;

[ IF NOT EXISTS ] has been in PostgreSQL since 9.1