Thread: How does "SELECT ... FOR UPDATE" work?

How does "SELECT ... FOR UPDATE" work?

From
Joshua Daniel Franklin
Date:
I am trying to build a small multiuser application.
The single-user mode works fine, but I want to be able
to lock some rows that are going to be updated.

I am trying to understand how to use "SELECT ... FOR UPDATE;"
to do this. With the psql client, I opened two sessions and did

"select * from iocc where id='100' for update;"

which returned the appropriate row. Then, in the *other* session,

"update iocc set zip = '71998' where id = '100';"

which returned "UPDATE 1" (I was expecting some error). I then
looked back in the first session and the row was indeed updated.
Obviously I'm missing something here.

I'm using RedHat 7.3 with postgresql-server-7.2.1-5 rpm.
Thanks.

Joshua Daniel Franklin
IOCC.COM



Re: How does "SELECT ... FOR UPDATE" work?

From
Tom Lane
Date:
Joshua Daniel Franklin <joshua@iocc.com> writes:
> Obviously I'm missing something here.

I think you forgot to issue a "BEGIN;" to open a transaction block.
The lock created by FOR UPDATE (or any other lock) is only held till
transaction commit.

            regards, tom lane