How to get column attributes query from table name using PostgreSQL?

后端 未结 3 1368
离开以前
离开以前 2020-12-13 15:49

I have a project and I need a query to get all attributes of the columns (Column Name, Position, Data Type, Not Null? and Comments) all this using table name.

I ach

3条回答
  •  不思量自难忘°
    2020-12-13 16:49

    Here's query against the system catalog that should fetch everything you need (with a bonus primary-key field thrown in for free).

    SELECT DISTINCT
        a.attnum as num,
        a.attname as name,
        format_type(a.atttypid, a.atttypmod) as typ,
        a.attnotnull as notnull, 
        com.description as comment,
        coalesce(i.indisprimary,false) as primary_key,
        def.adsrc as default
    FROM pg_attribute a 
    JOIN pg_class pgc ON pgc.oid = a.attrelid
    LEFT JOIN pg_index i ON 
        (pgc.oid = i.indrelid AND i.indkey[0] = a.attnum)
    LEFT JOIN pg_description com on 
        (pgc.oid = com.objoid AND a.attnum = com.objsubid)
    LEFT JOIN pg_attrdef def ON 
        (a.attrelid = def.adrelid AND a.attnum = def.adnum)
    WHERE a.attnum > 0 AND pgc.oid = a.attrelid
    AND pg_table_is_visible(pgc.oid)
    AND NOT a.attisdropped
    AND pgc.relname = 'TABLE_NAME'  -- Your table name here
    ORDER BY a.attnum;
    

    Which would return results like:

     num |    name     |             typ             | notnull |       comment       | primary_key 
    -----+-------------+-----------------------------+---------+---------------------+-------------
       1 | id          | integer                     | t       | a primary key thing | t
       2 | ref         | text                        | f       |                     | f
       3 | created     | timestamp without time zone | t       |                     | f
       4 | modified    | timestamp without time zone | t       |                     | f
       5 | name        | text                        | t       |                     | f
    
    • num: The column number
    • name: The column name
    • typ: the data type
    • notnull: Is the column defined as NOT NULL
    • comment: Any COMMENT defined for the column
    • primary_key: Is the column defined as PRIMARY KEY
    • default: The command used for the default value

提交回复
热议问题