4

I know I can use \d to list the schema. However, I need to make a front end application just to display attribute names of a table. How can I get the only attribute names out in PostgreSQL?

Thanks!

1 Answer 1

6

You need to query appropriate tables under pg_catalog or information_schema schemas. Run psql -E ... and then psql displays meta-data queries used in internal commands like \d, \dt, \dv, ...

information_schema is same as pg_catalog but more portalbe (it is defined in SQL standard). If your app uses postgres only then I would use pg_catalog instead of information_schema

For example, this query shows columns for attribute

SELECT a.attname,
  pg_catalog.format_type(a.atttypid, a.atttypmod),
  (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
   FROM pg_catalog.pg_attrdef d
   WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef),
  a.attnotnull, a.attnum
FROM pg_catalog.pg_attribute a
WHERE a.attrelid = 'attribute'::regclass AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum

UPDATE: You can use simple query like this:

SELECT attname 
FROM pg_catalog.pg_attribute 
WHERE attrelid = 'attribute'::regclass AND attnum > 0 AND NOT attisdropped

or use equivalent query:

SELECT column_name 
FROM information_schema.columns 
WHERE table_name = 'attribute' 
ORDER BY ordinal_position

If you have same table with the same name in multiple schemas you need to user schema name as well and query get slightly more complex.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for your answer. However, I still don't quite understand. The query you posted shows error near 'attribute'. I tried "select attname from pg_catalog.pg_attribute;" However, it shows more than what I need.
Sorry, attribute is my example table name :). What's the error message? This is from Postgres 8.4 -- maybe some copy & paste formatting issue. If you have table called 'my_table' then use ... WHERE a.attrelid = 'my_table'::regclass AND ...

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.