Re: R: [SQL] UPDATE and SELECT result difference

From: Jean-Luc Lachance <jllachan(at)nsd(dot)ca>
To: enr1(at)libero(dot)it, Andrea Giardina <andrea(dot)giardina(at)nethouse(dot)it>, pgsql-general(at)postgresql(dot)org
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: R: [SQL] UPDATE and SELECT result difference
Date: 2002-03-15 16:19:47
Message-ID: 3C921F23.C7477776@nsd.ca
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-sql

Hello again Enrico,

Your first UPDATE will update 1 record 3 times; there is only one record
updated.
The second UPDATE is not equivalant and will return an error as the
sub-select should not return more than one tuple.

But, you can write:

UPDATE tab_test1
SET campo1 = (
SELECT campo2
FROM tab_test2
WHERE tab_test1.cod = tab_test2.cod
ORDER BY campo2
LIMIT 1);

jll

Enrico Mangano wrote:
>
> Thank you, Jean-Luc!
>
> But now I would have another question about this:
>
> cod | campo1
> -----+---------
> 1 | valore1
> (1 row)
>
> cod | campo2
> -----+---------
> 1 | valore2
> 1 | valore3
> 1 | valore4
>
> targhettariodb=# update tab_test1 set campo1 = tab_test2.campo2 where
> tab_test1.cod = tab_test2.cod;
> UPDATE 1
> targhettariodb=# select * from tab_test1;
> cod | campo1
> -----+---------
> 1 | valore3
> (1 row)
>
> I think the value it has chosen is random, isn't it?
> So I can't have any control on it.
>
> The UPDATE query above is semantically equivalent to this:
> update tab_test1 set campo1 = (select campo2 from tab_test2, tab_test1
> where tab_test1.cod = tab_test2.cod);
> And this query(IMHO in a correct way) return an ERROR:
> targhettariodb=# update tab_test1 set campo1 = (select campo2 from
> tab_test2, tab_test1 where tab_test1.cod = tab_test2.cod);
> ERROR: More than one tuple returned by a subselect used as an
> expression.
>
> Isn't this an incongruence in SQL?
>
> Thanks,
> Enrico.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Lee Kindness 2002-03-15 16:36:25 Drop all databases objects except the database
Previous Message Thomas Lockhart 2002-03-15 15:53:26 Re: duplicating and date problem

Browse pgsql-sql by date

  From Date Subject
Next Message Tom Lane 2002-03-15 17:06:29 Re: Btree index extension question
Previous Message Kelly Burkhart 2002-03-15 16:03:26 optimizer tuning/forcing correct index use