How to generate the “create table” sql statement for an existing table in postgreSQL

后端 未结 19 2046
花落未央
花落未央 2020-11-28 17:49

I have created a table in postgreSQL. I want to look at the SQL statement used to create the table but cannot figure it out.

How do I get the create table

19条回答
  •  被撕碎了的回忆
    2020-11-28 18:21

    If you want to find the create statement for a table without using pg_dump, This query might work for you (change 'tablename' with whatever your table is called):

    SELECT                                          
      'CREATE TABLE ' || relname || E'\n(\n' ||
      array_to_string(
        array_agg(
          '    ' || column_name || ' ' ||  type || ' '|| not_null
        )
        , E',\n'
      ) || E'\n);\n'
    from
    (
      SELECT 
        c.relname, a.attname AS column_name,
        pg_catalog.format_type(a.atttypid, a.atttypmod) as type,
        case 
          when a.attnotnull
        then 'NOT NULL' 
        else 'NULL' 
        END as not_null 
      FROM pg_class c,
       pg_attribute a,
       pg_type t
       WHERE c.relname = 'tablename'
       AND a.attnum > 0
       AND a.attrelid = c.oid
       AND a.atttypid = t.oid
     ORDER BY a.attnum
    ) as tabledefinition
    group by relname;
    

    when called directly from psql, it is usefult to do:

    \pset linestyle old-ascii
    

    Also, the function generate_create_table_statement in this thread works very well.

提交回复
热议问题