First of all it's \d <table_name> (note the backslash \d not /d), but that's only available in the psql interactive terminal

My [objective] with this program is to get the table structure

You can use the SQL table information_schema.columns which carries the information you want

SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = '<table_name>';

    column_name     |     data_type     | is_nullable 
--------------------+-------------------+-------------
 column_a           | integer           | YES
 column_b           | boolean           | NO

Here's a list of the columns available for use: https://www.postgresql.org/docs/9.4/static/infoschema-columns.html

Snippet

import psycopg2
conn = psycopg2.connect(database='carto', user=..., password=...)

q = """                              
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = %s;
"""

cur = conn.cursor()
cur.execute(q, ('BADGES_SFR',))  # (table_name,) passed as tuple
cur.fetchall()

# Example Output 
[('column_a', 'integer', 'YES'),
 ('column_b', 'boolean', 'NO'),
 ...,
]

Tip for Jinja2/Flask integration:

Consider using psycopg2.extras.DictCursor, it'll make it easier for you to pull the information based on the column name (dict key) in your Flask template, because your'll a have a dict that you can access e.g. using row['data_type'], row['column_name'] etc.

Answer from bakkal on Stack Overflow
Top answer
1 of 2
8

First of all it's \d <table_name> (note the backslash \d not /d), but that's only available in the psql interactive terminal

My [objective] with this program is to get the table structure

You can use the SQL table information_schema.columns which carries the information you want

SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = '<table_name>';

    column_name     |     data_type     | is_nullable 
--------------------+-------------------+-------------
 column_a           | integer           | YES
 column_b           | boolean           | NO

Here's a list of the columns available for use: https://www.postgresql.org/docs/9.4/static/infoschema-columns.html

Snippet

import psycopg2
conn = psycopg2.connect(database='carto', user=..., password=...)

q = """                              
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = %s;
"""

cur = conn.cursor()
cur.execute(q, ('BADGES_SFR',))  # (table_name,) passed as tuple
cur.fetchall()

# Example Output 
[('column_a', 'integer', 'YES'),
 ('column_b', 'boolean', 'NO'),
 ...,
]

Tip for Jinja2/Flask integration:

Consider using psycopg2.extras.DictCursor, it'll make it easier for you to pull the information based on the column name (dict key) in your Flask template, because your'll a have a dict that you can access e.g. using row['data_type'], row['column_name'] etc.

2 of 2
5

If you only need the columns description:

>>> cur.execute('select * from t')
>>> description = cur.description
>>> print description
(Column(name='record_timestamptz', type_code=1184, display_size=None, internal_size=8, precision=None, scale=None, null_ok=None),)
>>> columns = description[0]
>>> print columns.name, columns.type_code
record_timestamptz 1184

For the data type name cache the pg_type relation at the application start and make it a dictionary:

cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

cursor.execute ('select oid, * from pg_type')

pg_type = dict([(t['oid'], t['typname']) for t in cursor.fetchall()])

cursor.execute ('select * from t')

for t in cursor.description:
    print t.name, t.type_code, pg_type[t.type_code]
Discussions

python - How to specify Schema in psycopg2 connection method? - Stack Overflow
Using the psycopg2 module to connect to the PostgreSQL database using python. Able to execute all queries using the below connection method. Now I want to specify a different schema than public to More on stackoverflow.com
🌐 stackoverflow.com
python - Get the names of all schemas with Psycopg2 - Stack Overflow
I'm trying to iterate all tables of a Postgresql DB in Python, to execute a query in each of them. I need to get the schema and table name of each of them in order to execute the queries, so I'd li... More on stackoverflow.com
🌐 stackoverflow.com
June 7, 2017
psycopg2 - Postgres DB Schema
Bonjour, ça date un peu mais est-ce que vous vous souvenez de la solution pour interroger un schéma non public ? Je rencontre exactement le même souci et je n'arrive toujours pas à trouver la solution. J'ai essayé d'ajouter des privilèges de lecture mais ça ne donne rien. J'utilise pgAdmin pour afficher les tables et il n'y a aucun souci, mais via script python j'ai 0 ligne d'affichée, par contre ça renvoie bien les noms de colonnes. Des conseils sil vous plaît ? Merci bien ! More on reddit.com
🌐 r/learnpython
5
1
October 30, 2023
python - Getting data from schema in psycopg2 - Stack Overflow
I try to connect to Postgres database inside my Python app. I use psycopg2 library. If I execute select statement like this: cursor.execute("""select schema_name from information_schema.schemata;... More on stackoverflow.com
🌐 stackoverflow.com
October 4, 2017
🌐
Bytes
bytes.com › home › forum › topic › python
Find out the schema with psycopg? - Post.Byes
December 22, 2005 - But neither of these > appear to give you table names. > > Is there something else I should look at?[/color] Yes, but as with so many of these things you'll have to accept it's a platform-specific (i.e. non-portable) solution, and it requires that you are running PostgreSQL 7.4 or higher. Under those circumstances you can query the metadata through the information schema. [color=blue][color=green][color=darkred] >>> import psycopg2 as db >>> conn = db.connect('dbn ame=billings user=steve password=xxxxx[/color][/color][/color] port=5432')[color=blue][color=green][color=darkred] >>> curs = conn.cursor() >>> curs.execute("" "select table_name from information_sch ema.tables[/color][/color][/color] ....
🌐
Pythontic
pythontic.com › database › postgresql › create table
Create a table in PostgreSQL using Python and Psycopg2
A table in PostgreSQL can be created using Python and Psycopg. An example is given which creates a table and prints the updated list of tables under current schema of the PostgreSQL database.
🌐
DNMTechs
dnmtechs.com › getting-tables-in-postgres-with-psycopg2
Getting Tables in Postgres with Psycopg2 – DNMTechs – Sharing and Storing Technology Knowledge
We then create a cursor object to execute queries. We execute a query to fetch all table names from the information_schema.tables view, filtering by the public schema. We fetch all the table names using the fetchall() method and print them one by one. Finally, we close the cursor and connection ...
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › psycopg2 - postgres db schema
r/learnpython on Reddit: psycopg2 - Postgres DB Schema
October 30, 2023 -

Hi, I need some assistance please. I'm trying to connect to a Postgres database that's hosted on AWS.

The database has multiple schemas. The schema I want to connect to is not the public one.

I connect but cannot execute queries on the none public schemas. I can list all schemas but just cannot query the schema I want. I am using the options tag in the connection string but still it cannot see tables.

When I query anything in public it can see all tables.

Any advice please.

🌐
MLJAR
mljar.com › docs › python-postgres-list-tables
Python show all tables from PostgreSQL
List all tables using the current connection and .env credentials. Use advanced options to show schemas.
🌐
GeeksforGeeks
geeksforgeeks.org › python › get-column-names-from-postgresql-table-using-psycopg2
Get column names from PostgreSQL table using Psycopg2 - GeeksforGeeks
July 23, 2025 - "select COLUMN_NAME from information_schema.columns where table_schema = 'SCHEMA_NAME' and table_name='TABLE_NAME'" Python3 · import psycopg2 conn = psycopg2.connect( database="geeks", user='postgres', password='root', host='localhost', port='5432' ) conn.autocommit = True with conn: with conn.cursor() as cursor: cursor.execute( "select COLUMN_NAME from information_schema.columns\ where table_name='products'") column_names = [row[0] for row in cursor] print("Column names:\n") for i in column_names: print(i) Output: Column names: product_no name price ·
🌐
GitHub
github.com › psycopg › psycopg2 › issues › 1294
cursor.copy_from table argument no longer accepting schema · Issue #1294 · psycopg/psycopg2
June 17, 2021 - Hi, In 2.8.6 and earlier, I was able to pass a schema.table argument cursor.copy_from: cursor.copy_from(f, table='schema.table') But this is no longer working on >2.9: UndefinedTable: relation "schema.table" does not exist
Author   psycopg
🌐
StrongDM
strongdm.com › blog › security
How to Show/List Tables in PostgreSQL (psql, SQL & pgAdmin)
October 24, 2025 - Expand the Schemas group option > public > Tables in the tree. This method uses code and APIs to list tables in Postgres. With code, for example, you can use programming languages like Python and Node.js to connect to your PostgreSQL database ...
🌐
MLJAR
mljar.com › notebooks › postgresql-python-show-tables
Show tables from PostgreSQL database
You can use show tables and columns recipes. """) # print the results print("Tables:") for table in cur.fetchall(): print(f"{table}") You can also tick show schema box, this will show database schema of each table.
🌐
GitHub
github.com › spotify › luigi › issues › 3198
[contrib.postgres] copy_from does not accept schema.table notation in most recent psycopg2 versions · Issue #3198 · spotify/luigi
September 7, 2022 - In this project, the PostgreSQL database contains several schemas, and some data may be added to tables which are not in default public schema through CopyToTable-derived tasks. However CopyToTable uses the cursor.copy_from method, which has been recently modified in psycopg2 API (see e.g psycopg/psycopg2#1294).
Author   spotify
🌐
Psycopg
psycopg.org › docs › usage.html
Basic module usage — Psycopg 2.9.12 documentation
>>> import psycopg2 # Connect to an existing database >>> conn = psycopg2.connect("dbname=test user=postgres") # Open a cursor to perform database operations >>> cur = conn.cursor() # Execute a command: this creates a new table >>> cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);") # Pass data to fill a query placeholders and let Psycopg perform # the correct conversion (no more SQL injections!)
🌐
DataCamp
datacamp.com › tutorial › tutorial-postgresql-python
Managing PostgreSQL Databases in Python with psycopg2 | DataCamp
March 21, 2025 - Learn how to create, connect to, and manage PostgreSQL databases using Python’s psycopg2 package.