10

I wish to list all the column names of a table using psycopg2 package of Python (2.7). But I am unable to execute the following query -

cur.execute("\d my_table");
psycopg2.ProgrammingError: syntax error at or near "\"

Is there an alternate as to how I can list the column names of a table using psycopg2 ? Please point out any duplicates. Thanks !

Utsav T
  • 1,515
  • 2
  • 24
  • 42

1 Answers1

7

Command line psql has some shortcuts like \d but it's not part of SQL. What you need is to query information_schema:

SELECT column_name FROM information_schema.columns WHERE table_name = 'my_table';

EDIT: It's really an important information that the command line psql -E will echo SQL queries used to implement \d and other backslash commands (whenever you use one of them in the psql prompt) as @piro has written in comment. This way you get what you want very easily.
Thanks @piro!

ElmoVanKielmo
  • 10,907
  • 2
  • 32
  • 46
  • 2
    None. But everething you can do with meta commands is also available by querying `information_schema` and/or `pg_catalog`. – ElmoVanKielmo Jul 21 '15 at 07:33
  • 5
    note that `psql -E` will emit the query used internally to implement `\d` and the other backslash commands, which is super-handy to explore the `pg_catalog`. – piro Jul 27 '15 at 16:24