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

后端 未结 19 2043
花落未央
花落未央 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:05

    Here is a bit improved version of shekwi's query.
    It generates the primary key constraint and is able to handle temporary tables:

    with pkey as
    (
        select cc.conrelid, format(E',
        constraint %I primary key(%s)', cc.conname,
            string_agg(a.attname, ', ' 
                order by array_position(cc.conkey, a.attnum))) pkey
        from pg_catalog.pg_constraint cc
            join pg_catalog.pg_class c on c.oid = cc.conrelid
            join pg_catalog.pg_attribute a on a.attrelid = cc.conrelid 
                and a.attnum = any(cc.conkey)
        where cc.contype = 'p'
        group by cc.conrelid, cc.conname
    )
    select format(E'create %stable %s%I\n(\n%s%s\n);\n',
        case c.relpersistence when 't' then 'temporary ' else '' end,
        case c.relpersistence when 't' then '' else n.nspname || '.' end,
        c.relname,
        string_agg(
            format(E'\t%I %s%s',
                a.attname,
                pg_catalog.format_type(a.atttypid, a.atttypmod),
                case when a.attnotnull then ' not null' else '' end
            ), E',\n'
            order by a.attnum
        ),
        (select pkey from pkey where pkey.conrelid = c.oid)) as sql
    from pg_catalog.pg_class c
        join pg_catalog.pg_namespace n on n.oid = c.relnamespace
        join pg_catalog.pg_attribute a on a.attrelid = c.oid and a.attnum > 0
        join pg_catalog.pg_type t on a.atttypid = t.oid
    where c.relname = :table_name
    group by c.oid, c.relname, c.relpersistence, n.nspname;
    

    Use table_name parameter to specify the name of the table.

提交回复
热议问题