VOOZH about

URL: https://www.geeksforgeeks.org/postgresql/postgresql-create-table-using-python/

⇱ PostgreSQL - Create table using Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

PostgreSQL - Create table using Python

Last Updated : 15 Jul, 2025

Creating tables in a PostgreSQL database using Python is a common task for developers working with databases. This process involves defining the structure of your data and ensuring that your database is optimized for efficient storage and retrieval.

In this article, we will walk through the steps of creating tables in PostgreSQL using Python.

Prerequisites:

  • psycopg2 module: A popular PostgreSQL adapter for Python, which allows you to connect to and interact with your PostgreSQL database.
  • Sample Database: A PostgreSQL database where you can create and manage tables.

Steps to Create a Table in PostgreSQL Using Python

To create a table in the database use the following steps:

  • First, create a CREATE TABLE statement
  • Second, establish a connection to the database using the 'connect()' function
  • Third, construct a cursor object by using the 'cursor()' method.
  • Now execute the above created CREATE TABLE statement using the 'execute()' function.

Example: Creating Tables in a School Database

To demonstrate the process, let's walk through an example where we create several tables in a PostgreSQL database named 'school'. We'll use a Python script named 'create_table.py', which includes a function called 'create_table()'.

To verify so use the below command through the client tool of the same database(ie, school):

\dt

Output:

This will successfully create the tables : 

  • 'student'
  • 'grade'
  • 'student_grade'
  • 'student_detail'
👁 PostgreSQL - Create table using Python

Best Practices for Creating Tables in PostgreSQL

  • Use consistent and descriptive names for tables and columns.
  • Choose appropriate data types for each column to ensure efficient storage and accurate data representation.
  • Define constraints such as PRIMARY KEY, FOREIGN KEY, and UNIQUE to enforce data integrity.
  • Consider adding indexes on columns that will be frequently searched or used in join operations.
Comment
Article Tags:

Explore