agora inbox for pgsql-sql@postgresql.org  
help / color / mirror / Atom feed
From: David G Johnston <david.g.johnston@gmail.com>
To: pgsql-sql@postgresql.org
Subject: Re: Update Returning as subquery
Date: Sun, 10 Aug 2014 11:10:54 -0700 (PDT)
Message-ID: <1407694253994-5814370.post@n5.nabble.com> (raw)
In-Reply-To: <F1134784-45F6-48C9-BA79-98F9BBE00051@ensieve.org>
References: <F1134784-45F6-48C9-BA79-98F9BBE00051@ensieve.org>
List-Unsubscribe: <mailto:majordomo@postgresql.org?body=unsub%20pgsql-sql>

pascal+postgres wrote
> Hi,
> 
> I want to update some values in a table, and need to count the number of
> values actually changed; but ROW_COUNT returns the number of total rows
> touched.
> 
> But this gives a syntax error:
> 
> SELECT count(*) INTO my_count
> FROM (
>   UPDATE stuff
>   SET value = maybe_null(key)
> --^
>   WHERE value IS NULL
>   RETURNING value ) AS t
> WHERE value IS NOT NULL;
> 
> Why is that forbidden? Isn't the purpose of a RETURNING clause to return
> values like a SELECT statement would, and shouldn't it therefore be
> allowed to occur in the same places?
> 
> 
> 
> I switched it around using a CTE in this case:
> 
> WITH new_values AS (
>   SELECT key, maybe_null(key) AS value
>   FROM stuff WHERE value IS NULL)
> UPDATE stuff AS s
> SET value = n.value
> FROM new_values AS n
> WHERE n.key = s.key
> AND n.value IS NOT NULL;
> 
> Which only touches rows that will be changed and returns a useful
> ROW_COUNT, but needs a join. 
> 
> Cheers,

The following should work...

WITH do_uodate AS (
UPDATE ... WHERE value IS NULL
RETURNING value
) 
SELECT count(*) FROM do_update WHERE value IS NOT NULL

I don't know why it doesn't work in subquery form but other than syntax this
and your first form are equivalent.

David J.




--
View this message in context: http://postgresql.1045698.n5.nabble.com/Update-Returning-as-subquery-tp5814366p5814370.html
Sent from the PostgreSQL - sql mailing list archive at Nabble.com.


-- 
Sent via pgsql-sql mailing list (pgsql-sql@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-sql



view thread (3+ messages)

Message-ID: <1407694253994-5814370.post@n5.nabble.com>
Permalink:  ../1407694253994-5814370.post@n5.nabble.com/
Also on:    postgresql.org/message-id/1407694253994-5814370.post@n5.nabble.com

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: david.g.johnston@gmail.com
  Subject: Re: Update Returning as subquery
  In-Reply-To: <1407694253994-5814370.post@n5.nabble.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox