Using Psycopg2, I need to test whether a postgresql table exists or not.
In a similar question, it is recommended to use the following test:
cursor.execute("select exists(select * from myDb.mytable_%s)" % complementName)
tableExists = cursor.fetchone()[0]
print(tableExists)
This works great if the table already exists, and returns True
, but it does not work if the table does not exist. Instead of returning False
like I would need, I get an error
ProgrammingError: relation "myDb.mytable_001" does not exist
What am I doing wrong? What should I do in order to get a False
statement if the table doesn't exist? Thanks for any help!
EDIT
Following advice in comments, I tried also:
tableExists = cursor.execute("SELECT 1 AS result FROM pg_database WHERE datname='mytable_001'")
and
tableExists = cursor.execute("SELECT EXISTS (SELECT 1 AS result FROM pg_tables WHERE schemaname = 'mySchema' AND tablename = 'mytable_001)')")
But both simply return None
, whether the table exists or not. However, I'm not sure of the syntax, maybe you can point out some novice mistake I may be making? Thanks!
EDIT 2 Finally the solution consisted in a combination of the latter query above, and fetching the boolean result as follows:
cursor.execute("SELECT EXISTS (SELECT 1 AS result FROM pg_tables WHERE schemaname = 'mySchema' AND tablename = 'mytable_001');")
tableExists = cursor.fetchone()[0]