Re: Update Returning as subquery

From: David G Johnston <david(dot)g(dot)johnston(at)gmail(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: Update Returning as subquery
Date: 2014-08-10 18:10:54
Message-ID: 1407694253994-5814370.post@n5.nabble.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-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.

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Marcin Krawczyk 2014-08-11 09:50:19 Re: function call
Previous Message Tom Lane 2014-08-10 17:17:48 Re: Update Returning as subquery