Skip to content
Advertisement

Increment a column value of an entity in an SQL table

I’ve set up the following table:

On inserting few rows, the table looks like this:

Now, while adding a new insert into the table, for example – INSERT INTO transactions (stock, qty, user_id) VALUES ('APPL', 3, 1) if ‘stock‘ and ‘user_id‘ match (as in the above example), i only want the quantity to be updated in the database. Such as in this case, the row 1 entity should have its ‘qty’ column value incremented by +3.

Is there a solution to this without using any ORM like SQLalchemy etc. ?

Advertisement

Answer

You want on conflict. First set up a unique constraint on the stock/user_id columns:

Then use this with an on conflict statement:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement