195

How can I get a list of column names and datatypes of a table in PostgreSQL using a query?

1
  • plsql \gdesc is also an option. The neat feature is it could describe entire queries(useful for complex adhoc ones) but it works for simplified scenario SELECT * FROM tab_name \gdesc as well. Nov 21, 2020 at 10:02

15 Answers 15

256
SELECT
    column_name,
    data_type
FROM
    information_schema.columns
WHERE
    table_name = 'table_name';

with the above query you can columns and its datatype

5
  • 7
    That won't give the right answer for user-defined types (e.g., Geometry and Geography columns created by ogr2ogr, which are of the form geometry(Geometry,[SRID])).
    – GT.
    Jul 13, 2016 at 4:51
  • 4
    One might also use table_catalog = 'my_database' and table_schema = 'my_schema' in order to get only columns from a specific table of a specific schema of a specific database. Mar 24, 2017 at 16:46
  • 2
    May I suggest to everyone, if you are looking to build on this code. Use the pg_catalog and not the information_schema. The information_schema has some pretty easy and universal SQL, however it is slower because it is higher level. Dec 22, 2020 at 14:51
  • @DanielL.VanDenBosch however, pg_catalog is subject to breaking changes between postgres versions.
    – OrangeDog
    Jul 6 at 16:21
  • 1
    @MarcoMannes or table_schema = current_schema(). For postgres the information_schema only contains data for the current database, so you don't have to worry about that.
    – OrangeDog
    Jul 6 at 16:34
229

Open psql command line and type :

\d+ table_name
5
  • 4
    I don't understand why this isn't the most upvoted answer.
    – mjezzi
    Apr 12, 2018 at 20:18
  • 39
    This is incomplete as OP may want to do this programmatically in SQL code, not just via psql.
    – Lucat
    Aug 7, 2018 at 10:42
  • 3
    Postgres does it programmatically, so just start postgres with the '-E' flag: psql -E and for every backslash command the respective SQL will be displayed before the result of the command.
    – karatedog
    Aug 11, 2020 at 7:38
  • 3
    Presuming OP has access to psql makes this answer a little out of scope. Having postgres does not presume proficiency or the ability to access psql. Feb 18, 2021 at 4:17
  • I was initially dismissive of this answer, but surprisingly, this worked out the best for me when creating a dblink. I just copied and pasted the output into a spreadsheet, split by | got the first two columns, added a comma column and a ); at the end and we have a dblink query.
    – nurettin
    Mar 18, 2022 at 8:54
32
SELECT
        a.attname as "Column",
        pg_catalog.format_type(a.atttypid, a.atttypmod) as "Datatype"
    FROM
        pg_catalog.pg_attribute a
    WHERE
        a.attnum > 0
        AND NOT a.attisdropped
        AND a.attrelid = (
            SELECT c.oid
            FROM pg_catalog.pg_class c
                LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
            WHERE c.relname ~ '^(hello world)$'
                AND pg_catalog.pg_table_is_visible(c.oid)
        );

Change the hello world with your table name

More info on it : http://www.postgresql.org/docs/9.3/static/catalog-pg-attribute.html

1
  • 3
    Works, but why are you using c.relname ~ '^(hello world)$ instead of simply c.relname = 'hello world'?
    – Thomas
    Apr 1, 2019 at 12:26
26

Don't forget to add the schema name in case you have multiple schemas with the same table names.

SELECT column_name, data_type 
FROM information_schema.columns
WHERE table_name = 'your_table_name' AND table_schema = 'your_schema_name';

or using psql:

\d+ your_schema_name.your_table_name
22

A version that supports finding the column names and types of a table in a specific schema, and uses JOINs without any subqueries

SELECT
    pg_attribute.attname AS column_name,
    pg_catalog.format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS data_type
FROM
    pg_catalog.pg_attribute
INNER JOIN
    pg_catalog.pg_class ON pg_class.oid = pg_attribute.attrelid
INNER JOIN
    pg_catalog.pg_namespace ON pg_namespace.oid = pg_class.relnamespace
WHERE
    pg_attribute.attnum > 0
    AND NOT pg_attribute.attisdropped
    AND pg_namespace.nspname = 'my_schema'
    AND pg_class.relname = 'my_table'
ORDER BY
    attnum ASC;
1
  • 2
    This is my favorite answer because it accomplishes 2 things. It uses the pg_catalog and it forces you specify the schema. If you are cramming everything thing in the public schema, I personally believe that is a bad strategy. As your project grows, it will be difficult to keep things organized. IMHO Dec 22, 2020 at 15:23
9

Updated Pratik answer to support more schemas and nullables:

SELECT
    "pg_attribute".attname                                                    as "Column",
    pg_catalog.format_type("pg_attribute".atttypid, "pg_attribute".atttypmod) as "Datatype",

    not("pg_attribute".attnotnull) AS "Nullable"
FROM
    pg_catalog.pg_attribute "pg_attribute"
WHERE
    "pg_attribute".attnum > 0
    AND NOT "pg_attribute".attisdropped
    AND "pg_attribute".attrelid = (
        SELECT "pg_class".oid
        FROM pg_catalog.pg_class "pg_class"
            LEFT JOIN pg_catalog.pg_namespace "pg_namespace" ON "pg_namespace".oid = "pg_class".relnamespace
        WHERE
            "pg_namespace".nspname = 'schema'
            AND "pg_class".relname = 'table'
    );
7
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';
1
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Nov 21, 2020 at 10:16
3

To make this topic 'more complete'.

I required the column names and data types on a SELECT statement (not a table).

If you want to do this on a SELECT statement instead of an actual existing table, you can do the following:

DROP TABLE IF EXISTS abc;
CREATE TEMPORARY TABLE abc AS
-- your select statement here!
SELECT 
    *
FROM foo
-- end your select statement
;

select column_name, data_type 
from information_schema.columns 
where table_name = 'abc';
DROP IF EXISTS abc;

Short explanation, it makes a (temp) table of your select statement, which you can 'call' upon via the query provided by (among others) @a_horse_with_no_name and @selva.

Hope this helps.

3

I was looking for a way to get column names with data types without PSQL cl, directly from pgAdmin 4, and found a workaround. Adding one more option:

right-click desired database > generate ERD(Beta) > Generate SQL(or Alt+Ctrl+S) and pgAdmin 4 will open Query Editor where you can find all tables with column names and data types: Query Editor

0
3
 --how to get a list column names and datatypes of a table in PostgreSQL?


    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
    ;
1
  • Please include context with your code. Also, how do you expand this to other schemas? Dec 22, 2020 at 15:31
2

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';

1
query = "SELECT column_name FROM information_schema.columns WHERE table_schema = 'schema_name' AND table_name = 'table_name'"
qry = execute(query)
print(qry)
3
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
    – XMehdi01
    Jul 10 at 21:47
  • 1
    @XMehdi01: Why doesn’t it answer the question? It looks like an answer to me. Is this due to a technical issue? E.g., do you believe the answer is incorrect? Because, otherwise, it’s still proposing a solution. Jul 23 at 0:49
  • 1
    That said, @kamran-kausar, this would be a much more valuable answer if you explained how your approach is different from the validated answers, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation? Jul 23 at 0:56
0

Below will list all the distinct data types of all the table in the provided schema name.

\copy (select distinct data_type, column_name from information_schema.columns where table_name in (SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema' and schemaname = '<Your schema name>')) to 'datatypes.csv'  delimiter as ',' CSV header
0

create a new function to get the table info

CREATE FUNCTION xdesc(in t varchar) RETURNS table(column_name varchar, 
data_type varchar) AS $$
  SELECT column_name, data_type 
  FROM information_schema.columns
WHERE table_name = $1 
$$ LANGUAGE SQL;


select xdesc('rs_rail_job_index')
0

I found @Pratik's answer to be the thing, but it didn't work for me for some reason. I've rewritten it in a more consise, if I may, manner. It's easier to understand, it supports schemas and actually works for me (postgres 15). No joins.

SELECT
    attname AS colname,
    pg_catalog.format_type(atttypid, atttypmod) AS coltype
FROM
    pg_catalog.pg_attribute
WHERE
    attnum > 0 AND
    NOT attisdropped AND
    attrelid = 'your table name'::regclass
ORDER BY
    attnum ASC
;

P.S. It also supports composite types (which I actually needed very much). It would return a string like this: schemaname.tablename.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.