Thread: Update Query Problem

Update Query Problem

From
Jeng Yu
Date:
Hi People!

I'm doing an application and I've chosen postgresql
for the backend db. I need to use SQL update command
like this in my application:

update mytable set x='20' where id='someid' order by
id limit 1;

In other words, I want to update just one row of the
table if there are more than one row that the query
finds.

It doesn't work for me in postgresql. What's the way I
can do this in postgresql? Please forgive me if this
has been answered before. Please point me to the right
doc. I couldn't readily find the answer.

Thanks,

Jeng Yu




Re: Update Query Problem

From
"A. Kretschmer"
Date:
am  Fri, dem 10.10.2008, um 12:38:24 +0100 mailte Jeng Yu folgendes:
> Hi People!
>
> I'm doing an application and I've chosen postgresql
> for the backend db. I need to use SQL update command
> like this in my application:
>
> update mytable set x='20' where id='someid' order by
> id limit 1;

Du you have a primary key?

If you don't have a pk, you can use the ctid:

test=# create table a ( id int, val int);
CREATE TABLE
test=# insert into a values (1,1);
INSERT 0 1
test=# insert into a values (1,1);
INSERT 0 1
test=# insert into a values (1,1);
INSERT 0 1
test=# select * from a;
 id | val
----+-----
  1 |   1
  1 |   1
  1 |   1
(3 rows)

test=# begin;
BEGIN
test=# update a set val=2 where ctid=(select ctid from a where id=1 limit 1);
UPDATE 1
test=# select * from a;
 id | val
----+-----
  1 |   1
  1 |   1
  1 |   2
(3 rows)


Andreas
--
Andreas Kretschmer
Kontakt:  Heynitz: 035242/47150,   D1: 0160/7141639 (mehr: -> Header)
GnuPG-ID:   0x3FFF606C, privat 0x7F4584DA   http://wwwkeys.de.pgp.net