Create new table using python and PostgreSQL

To create new table give it a name and all its columns, provide data type for every column, and you're done!

This notebook was created with MLJAR Studio

MLJAR Studio is Python code editior with interactive code recipes and local AI assistant.
You have code recipes UI displayed at the top of code cells.

Documentation

All required packages are automatically imported by MLJAR Studio for you so you don't have to worry about them.

# import packages
import psycopg
import os
from dotenv import load_dotenv
from psycopg import sql

Make sure you opened a connection in your notebook. To learn how to do it, check out open and test database connection example notebook.

# load credentials from .env file:
load_dotenv(override=True)

# get the credentials
def create_new_connection():
    try:
        conn = psycopg.connect(
            dbname=os.getenv("POSTGRES_DB_NAME"),
            user=os.getenv("POSTGRES_USERNAME"),
            password=os.getenv("POSTGRES_PASSWORD"),
            host=os.getenv("POSTGRES_HOST"),
            port=os.getenv("POSTGRES_PORT"),
        )
        return conn
    # check for errors
    except psycopg.Error as e:
        raise psycopg.Error(f"""
Error occurred while establishing connection: 
    {e}

Maybe you provided wrong credentials, use define new connection recipe to edit them.
Other option is that database server is down or you dont have the right acces to this database.
            """)

# open new connection:
conn = create_new_connection()

Provide names for every column and its data type. Type them in a comma separeted list without any whitecpace and without traling comma. Remember that number of columns names needs to be equal to number of data types. Don't forget to name the table.

# if connection was used and closed it is reopen here
if conn.closed:
    conn = create_new_connection()

# run query
with conn:
    with conn.cursor() as cur:

        # create table
        try:
            cur.execute(
                sql.SQL(
                    """CREATE TABLE {table} (
						{col1} serial,
						{col2} int,
						{col3} text
                    );"""
                ).format(
                    table=sql.Identifier("my_new_table"),
					col1=sql.Identifier("id"),
					col2=sql.Identifier("number"),
					col3=sql.Identifier("data")
                )
            )
        # check for errors
        except psycopg.ProgrammingError as e:
            raise psycopg.ProgrammingError(f"""
Problem creating table:
    {e}

Are you sure table and columns names are all unique?
Is every data type a valid psotgreSQL data type?
            """)

Show all tables recipe is used here to demonstrate that creating table worked. If you want to learn how to use this recipe check out show tables from database notebook.

# if connection was used and closed it is reopen here
if conn.closed:
    conn = create_new_connection()

# run query
with conn:
    with conn.cursor() as cur:

        # query db
        try:
            cur.execute("""
                SELECT table_name
                FROM information_schema.tables
                WHERE table_type = 'BASE TABLE'
                AND table_schema NOT IN ('pg_catalog', 'information_schema');
            """)
        # check for errors
        except psycopg.ProgrammingError as e:
            raise psycopg.ProgrammingError(f"""
Problem running query:
    {e}

Did you spell everything correctly?
You can use show tables and columns recipes.
            """)

        # print the results
        print("Tables:")
        for table in cur.fetchall():
            print(f"{table}")

Conclusions

Learning how to add new tables is a big stepping stone on the journey to mastering SQL, with this recipe your learn the basics and get a head start compared to the rest.

Recipes used in the postgresql-python-create-table.ipynb

All code recipes used in this notebook are listed below. You can click them to check their documentation.

Packages used in the postgresql-python-create-table.ipynb

List of packages that need to be installed in your Python environment to run this notebook. Please note that MLJAR Studio automatically installs and imports required modules for you.

psycopg>=3.2.1

python-dotenv>=1.0.1