7

I'm unable to delete a specific table in my PostgreSQL database. That table is called "user". When I try to run the snippet of code below,

    import psycopg2
    conn = psycopg2.connect("dbname='mydatabase' user='postgres' host='localhost' password='mypassword'")
    cur = conn.cursor()
    cur.execute("DROP TABLE user;")  
    conn.commit()
    conn.close()

It spits out the following error

  Traceback (most recent call last):
    File "dev_psycog.py", line 20, in <module>
       cur.execute("DROP TABLE user;")  
  psycopg2.ProgrammingError: syntax error at or near "user"
  LINE 1: DROP TABLE user;

I can delete any other table in my database just fine, but I can't seem to delete my table called "user". Is it because "user" is a reserved keyword?

2
  • 1
    Try drop table 'user' Commented Aug 29, 2016 at 20:10
  • So I got a similar error when I wrapped it single quotes. But it worked when i wrapped it with double quotes. Thank you Commented Aug 29, 2016 at 20:16

1 Answer 1

8

Quote "user" as below

import psycopg2
conn = psycopg2.connect("dbname='mydatabase' user='postgres' host='localhost' password='mypassword'")
cur = conn.cursor()
cur.execute('DROP TABLE "user";')  
conn.commit()
conn.close()

See here.

There is a second kind of identifier: the delimited identifier or quoted identifier. It is formed by enclosing an arbitrary sequence of characters in double-quotes (").

Sign up to request clarification or add additional context in comments.

2 Comments

Wrapping user with double quotes did the trick. Single quotes still gives the same error that I encountered. Thank you
@user3635123 accept as answer if it solved your problem

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.