With the following query, we can get a list of column names and datatype of a table in PostgreSQL.
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)
);
More info on it : http://www.postgresql.org/docs/9.3/static/catalog-pg-attribute.html
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'
);
select column_name,data_type
from information_schema.columns
where table_name = 'table_name';
with the above query you can columns and its datatype
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.
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;
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