Re: easy task: concurrent select-updates

From: Kevin McConnell <kevin(dot)mcconnell(at)gmail(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: easy task: concurrent select-updates
Date: 2009-09-03 19:05:17
Message-ID: 372194e70909031205i7ca1074o46f3fdc67cf613c6@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

> CREATE OR REPLACE FUNCTION public.getmsg() RETURNS integer LANGUAGE plpgsql
> AS $function$
> declare
>       rec record;
> begin
>       for rec in select id from msg where busy = false order by id loop
>               update msg set busy = true where id = rec.id and busy = false;
>               if found then
>                       return rec.id;
>               end if;
>       end loop;
>       return -1;
> end;
> $function$

I think you could also do something roughly similar in a statement by
using a RETURNING clause on the update, such as:

update msg set busy = true where id = (select min(id) from msg where
busy = false) returning *;

Cheers,
Kevin

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Alvaro Herrera 2009-09-03 19:08:36 Re: Create language PLPERL error
Previous Message Shakil Shaikh 2009-09-03 19:02:04 Re: Create language PLPERL error