Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: Unable to drop a specific table named "user"

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?

like image 599
user3635123 Avatar asked Aug 29 '16 20:08

user3635123


People also ask

How do I force drop a table in PostgreSQL?

You can remove table(s) from the database in PostgreSQL by using the statement DROP TABLE. It destroys the table with the indexes, rules, triggers, and constraints related to that table. The syntax is as follows: DROP TABLE [IF EXISTS] table_name [CASCADE | RESTRICT];

How do I drop a user in PostgreSQL?

To delete a Postgres role, run the following command in the PSQL client: DROP ROLE [IF EXISTS] <name>; The DROP USER statement is an alias for DROP ROLE .

Is user a reserved word in PostgreSQL?

user is a reserved word and it's usually not a good idea use reserved words for identifiers (tables, columns). If you insist on doing that you have to put the table name in double quotes: create table "user" (...); But then you always need to use double quotes when referencing the table.

What is drop cascade in PostgreSQL?

In PostgreSQL, the CASCADE option is used with the DROP TABLE statement to drop/delete a table and its dependent objects. To do so, specify the DROP TABLE command followed by the table name and then write the CASCADE to drop a table along with its dependent objects.


1 Answers

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 (").

like image 103
Atilla Ozgur Avatar answered Sep 20 '22 00:09

Atilla Ozgur