PostgreSQL - Create table using Python Last Updated : 15 Jul, 2025 Comments Improve Suggest changes Like Article Like Report 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 PythonTo create a table in the database use the following steps:First, create a CREATE TABLE statementSecond, establish a connection to the database using the 'connect()' functionThird, 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 DatabaseTo 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()'. Python import psycopg2 from config import config def create_tables(): """ create tables in the PostgreSQL database""" commands = ( """ CREATE TABLE student ( student_id SERIAL PRIMARY KEY, student_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE grade ( grade_id SERIAL PRIMARY KEY, grade_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE student_grade ( grade_id INTEGER PRIMARY KEY, file_extension VARCHAR(5) NOT NULL, drawing_data BYTEA NOT NULL, FOREIGN KEY (grade_id) REFERENCES grade (grade_id) ON UPDATE CASCADE ON DELETE CASCADE ) """, """ CREATE TABLE student_detail ( student_id INTEGER NOT NULL, grade_id INTEGER NOT NULL, PRIMARY KEY (student_id , grade_id), FOREIGN KEY (student_id) REFERENCES student (student_id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (grade_id) REFERENCES grade (grade_id) ON UPDATE CASCADE ON DELETE CASCADE ) """) conn = None try: # read the connection parameters params = config() # connect to the PostgreSQL server conn = psycopg2.connect(**params) cur = conn.cursor() # create table one by one for command in commands: cur.execute(command) # close communication with the PostgreSQL database server cur.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_tables() 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'Best Practices for Creating Tables in PostgreSQLUse 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. Create Quiz Comment D ddeevviissaavviittaa Follow 0 Improve D ddeevviissaavviittaa Follow 0 Improve Article Tags : PostgreSQL postgreSQL-managing-table Explore BasicsWhat is PostgreSQL - Introduction2 min readInstall PostgreSQL on Windows2 min readInstall PostgreSQL on Mac3 min readDatabase OperationsPostgreSQL - Create Database5 min readPostgreSQL - Loading a Database3 min readPostgreSQL ALTER DATABASE3 min readPostgreSQL - Rename Database4 min readPostgreSQL - Show Databases3 min readData TypesPostgreSQL - Data Types5 min readPostgreSQL - Boolean Data Type4 min readPostgreSQL - CHAR Data Type5 min readPostgreSQL - VARCHAR Data Type3 min readPostgreSQL - NUMERIC Data Type5 min readPostgreSQL - Date Data Type4 min readPostgreSQL - TIME Data Type4 min readPostgreSQL - JSON Data Type4 min readPostgreSQL - CREATE DOMAIN3 min readQuerying TablesPostgreSQL - SELECT3 min readPostgreSQL - ORDER BY clause2 min readPostgreSQL - WHERE clause6 min readPostgreSQL FETCH Clause4 min readPostgreSQL - IN operator4 min readPostgreSQL - HAVING clause4 min readPostgreSQL - GROUP BY clause4 min readPostgreSQL - LIKE operator5 min readPostgreSQL - BETWEEN Operator3 min readTable OperationsPostgreSQL - CREATE TABLE5 min readPostgreSQL - SELECT INTO4 min readPostgreSQL - CREATE SEQUENCE4 min readPostgreSQL - ALTER TABLE6 min readPostgreSQL - ADD COLUMN4 min readPostgreSQL - DROP COLUMN2 min readPostgreSQL - Rename Table2 min readPostgreSQL - DROP TABLE5 min readPostgreSQL - TRUNCATE TABLE4 min readPostgreSQL - Copy a Table3 min readPostgreSQL - Comparing Tables3 min readPostgreSQL - Show Tables4 min readModifying DataPostgreSQL - INSERT4 min readPostgreSQL - Insert Multiple Values in Various Rows3 min readPostgreSQL UPDATE Statement5 min readPostgreSQL - DELETE4 min readPostgreSQL - Upsert4 min readConditionalsPostgreSQL - CASE3 min readPostgreSQL COALESCE5 min readPostgreSQL - NULLIF() Function4 min readPostgreSQL - CAST3 min readControl FlowPostgreSQL - IF Statement5 min readPostgreSQL - CASE Statement4 min readPostgreSQL - Loop Statement3 min readPostgreSQL - While Loops4 min readPostgreSQL - Exit Statement3 min readPostgreSQL - Continue3 min readTransactions & ConstraintsPostgreSQL - Transactions4 min readPostgreSQL - COMMIT4 min readPostgreSQL - Primary Key4 min readPostgreSQL - Foreign Key5 min readPostgreSQL - CHECK Constraint2 min readPostgreSQL - UNIQUE Constraint3 min readPostgreSQL - NOT NULL Constraint3 min readJOINS & SchemasPostgreSQL - Joins5 min readPostgreSQL - LEFT JOIN5 min readPostgreSQL - INNER JOIN2 min readPostgreSQL - FULL OUTER JOIN4 min readPostgreSQL - SELF JOIN4 min readPostgreSQL - Schema5 min readPostgreSQL - CREATE SCHEMA5 min readPostgreSQL - DROP SCHEMA4 min readPostgreSQL - ALTER SCHEMA3 min read Like