Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FOR UPDATE NOWAIT doesn't work

Tags:

sql

postgresql

There are two queries:

1.

BEGIN;
SELECT * FROM "Users"
WHERE "Users"."Name" = 'user0'
FOR UPDATE NOWAIT ;

select pg_sleep(30);

END;

2.

BEGIN;
UPDATE "Users"
SET "Respect" = 2
WHERE "Users"."Name" = 'user0';
END;

As I use NOWAIT I expect that the second query will return error but it doesn't work for me. The second query just hangs and waits for the first one. What did I miss? I tried on 9.2-9.4 Postgres.

like image 291
Andrei Orlov Avatar asked Jul 19 '26 07:07

Andrei Orlov


1 Answers

NOWAIT affects the statement it's in. It doesn't affect other statements that want to wait rather than reporting an error.

To have your second query immediately raise an error if it can't lock rows, you'll need to rewrite it to use select ... for update nowait, then update.... The update statement alone doesn't have a nowait option.

BEGIN transaction;
select "Respect" from "Users" where "Name" = 'user0' for update nowait;

UPDATE "Users"
SET "Respect" = 2
WHERE "Users"."Name" = 'user0';
END;
like image 197
Mike Sherrill 'Cat Recall' Avatar answered Jul 22 '26 00:07

Mike Sherrill 'Cat Recall'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!