Using PostGRE - Executing Queries - Error Unexplainable

Hi - Can someone explain why I am returning this error? I’ve basically at this point recreated your answer but the only answer the module will take is your answer.

Here is the error:

IntegrityError: duplicate key value violates unique constraint “notes_pkey”
DETAIL: Key (id)=(1) already exists.

# conn = psycopg2.connect("dbname=dq user=dq")
# cur = conn.cursor()
# cur.execute("INSERT INTO notes VALUES (1, 'Do more missions on Dataquest.', 'Dataquest reminder');")
# conn.commit()
# cur.execute("SELECT * from notes;")
# rows = cur.fetchall()
# print(rows)
# conn.close()

conn = psycopg2.connect("dbname=dq user=dq")
cur = conn.cursor()
cur.execute("INSERT INTO notes VALUES (1, 'Do more missions on Dataquest.', 'Dataquest reminder');")
conn.commit()
cur.execute("SELECT * FROM notes;")
rows = cur.fetchall()
print(rows)
conn.close()

Hey. Sorry for the delay.

What screen is this happening on? The error is telling you that a row whose id column is 1 already exists in the table, so it won’t allow you to insert another row with that value.

No sweat Bruno.

https://app.dataquest.io/m/114/using-postgresql/7/executing-queries

Hi @eugeniosp3,

Your answer is correct. The problem is that probably at some point before you have executed that screen successfully. By doing so, that row as added to the table. The next time you run your code, you get a conflict because it uses an already existing key: 1.

After connecting, delete all contents of the table, like so:

cur.execute("DELETE FROM notes;")

Then your solution will work :slight_smile:

Let me know if it helps.

6 Likes

Thanks @Francois. I was able to get through the mission. :smiley:

I encountered the same problem and solved with your advice. Thanks @Francois