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?
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];
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 .
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.
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.
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 (").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With