17

I tried to learn about postgresql using python. I want to create condition CREATE DATABASE IF NOT EXISTS, but I always get an error. The error is :

File "learn_postgres.py", line 27, in InitDatabase
cursor.execute("CREATE DATABASE IF NOT EXISTS python_db") psycopg2.ProgrammingError: syntax error at or near "NOT"
LINE 1: CREATE DATABASE IF NOT EXISTS python_db

6
  • 2
    What is the version of Postgres you're using? The 'if not exists' clause is supported since 9.1. Commented Jun 13, 2017 at 3:42
  • Oh yap, I use 9.6 version. So, what should i do if i want teh condition like that ?? @9000 Commented Jun 13, 2017 at 3:49
  • @9000 Are you sure that it is valid syntax for create database statement? I do not see any if not exists there... Commented Jun 13, 2017 at 4:04
  • try CREATE DATABASE python_db instead. Commented Jun 13, 2017 at 4:05
  • @HaleemurAli That's working, but i want create condition if database not exists, my code will create database as automatic. Commented Jun 13, 2017 at 4:17

4 Answers 4

32

Postgres does not support the condition IF NOT EXISTS in the CREATE DATABASE clause, however, IF EXISTS is supported on DROP DATABASE

There are two options:

  1. Drop & Recreate (WARNING: This will result in losing any information stored in the database, do this only if you don't care about the stored data)

     cursor.execute('DROP DATABASE IF EXISTS python_db')
     cursor.execute('CREATE DATABASE python_db')
     # rest of the script
    
  2. Check the catalog first & branch the logic in python

     cursor.execute("SELECT 1 FROM pg_catalog.pg_database WHERE datname = 'python_db'")
     exists = cursor.fetchone()
     if not exists:
         cursor.execute('CREATE DATABASE python_db')
     # rest of the script
    
Sign up to request clarification or add additional context in comments.

Comments

5

You could query from pg_catalog.pg_database to check if the database is exist like this:

SELECT datname FROM pg_catalog.pg_database WHERE datname = 'python_db'

Then from here you can add the logic to create your db.

Comments

4
from psycopg2 import sql
from psycopg2.errors import DuplicateDatabase

...
conn.autocommit = True
cursor = conn.cursor()

try:
    cursor.execute(sql.SQL('CREATE DATABASE {}').format(sql.Identifier(DB_NAME)))
except DuplicateDatabase:
    pass

Comments

0

Answer29 shoot be: 2. check the catalog first & branch the logic in python

SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = TEST'"
cursor.execute(SQL)
exists = cursor.fetchone()

if exists == 'None':
    SQL = 'create database TEST'
    cursor.execute(SQL)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.