D
D
dfhkjhg2020-12-06 18:05:38
PostgreSQL
dfhkjhg, 2020-12-06 18:05:38

How to add data to table and update user if condition is met?

INSERT INTO inventory (itemid, created_at, status, userid) 
SELECT UNNEST ($1::bigint[]), $2, 0, $3
WHERE EXISTS (  
        SELECT balance FROM users 
        WHERE id = $3 AND balance >= $4::numeric
)

Here the query works, so if the user has enough money on the balance, we add items to the inventory
. And after adding the balance, we also need to reduce the balance by the amount of the purchase

UPDATE users 
SET balance -= $4::numeric


How? Where to add this request?
I just started learning sql.
And if it's not difficult, you can comment on the request if something is wrong in it

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2020-12-06
@dfhkjhg

Where to add this request?

into a transaction.
BEGIN;
INSERT ...;
UPDATE ...;
COMMIT;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question