How to get a list column names and datatype of a table in PostgreSQL?

前端 未结 11 2148
[愿得一人]
[愿得一人] 2020-12-02 10:02

With the following query, we can get a list of column names and datatype of a table in PostgreSQL.

相关标签:
11条回答
  • 2020-12-02 10:48

    Open psql command line and type :

    \d+ table_name
    
    0 讨论(0)
  • 2020-12-02 10:53

    without mentioning schema also you can get the required details Try this query->

    select column_name,data_type from information_schema.columns where table_name = 'table_name';

    0 讨论(0)
  • 2020-12-02 11:00
        SELECT DISTINCT
            ROW_NUMBER () OVER (ORDER BY pgc.relname , a.attnum) as rowid , 
            pgc.relname as table_name ,
            a.attnum as attr,
            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)
        LEFT JOIN pg_catalog.pg_namespace n ON n.oid = pgc.relnamespace
    
        WHERE 1=1 
            AND pgc.relkind IN ('r','')
            AND n.nspname <> 'pg_catalog'
            AND n.nspname <> 'information_schema'
            AND n.nspname !~ '^pg_toast'
    
        AND a.attnum > 0 AND pgc.oid = a.attrelid
        AND pg_table_is_visible(pgc.oid)
        AND NOT a.attisdropped
        ORDER BY rowid
        ;
    
    0 讨论(0)
  • 2020-12-02 11:00

    To get information about the table's column, you can use:

    \dt+ [tablename]
    

    To get information about the datatype in the table, you can use:

    \dT+ [datatype]
    
    0 讨论(0)
  • 2020-12-02 11:04
    SELECT column_name,data_type 
    FROM information_schema.columns 
    WHERE
    table_name = 'your_table_name' 
    AND table_catalog = 'your_database_name' 
    AND table_schema = 'your_schema_name';
    
    0 讨论(0)
提交回复
热议问题