0

I have a Postgres query which I execute in Python like so

cursor.execute('INSERT INTO my_data(id, val, bonus) VALUES (1, 2, 3) ON CONFLICT (id) DO UPDATE SET val = ex.val;')

I'd like to be able to tell if a fresh insert is happening to decide some later logic on the calling side. Outside of doing an extra read before attempting the upsert, is there a way of doing this? For example, checking a return code/message on whether the conflict was triggered

Madden
  • 1,024
  • 1
  • 9
  • 27

2 Answers2

2

After the execute, check cursor.rowcount to get the number of affected rows.

If that is 1, a row was inserted. If it is 0, an existing row was updated.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
0

Re. Laurenz's answer - using execute.many cursor.rowcount returns the total rows combined or updated (not only those inserted).

dreadedhamish
  • 31
  • 1
  • 3