Execute the a SQL statement in 'psql' to get the column names of a PostgreSQL table. SELECT column_name FROM INFORMATION_SCHEMA. COLUMNS WHERE TABLE_NAME = 'some_table'; NOTE: Make sure to replace the some_table string that's enclosed in single quotes with an actual table name before you execute the SQL statement.
To get the column name of a table we use sp_help with the name of the object or table name. sp_columns returns all the column names of the object. The following query will return the table's column names: sp_columns @table_name = 'News'
Open psql
command line and type :
\d+ table_name
SELECT
column_name,
data_type
FROM
information_schema.columns
WHERE
table_name = 'table_name';
with the above query you can columns and its datatype
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
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
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;
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'
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With