From: pascal+postgres@ensieve.org
To: pgsql-sql@postgresql.org
Subject: Update Returning as subquery
Date: Sun, 10 Aug 2014 17:15:20 +0100
Message-ID: <F1134784-45F6-48C9-BA79-98F9BBE00051@ensieve.org> (raw)
List-Unsubscribe: <mailto:majordomo@postgresql.org?body=unsub%20pgsql-sql>
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,
--
Pascal Germroth
--
Sent via pgsql-sql mailing list (pgsql-sql@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-sql
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: pascal+postgres@ensieve.org
Subject: Re: Update Returning as subquery
In-Reply-To: <F1134784-45F6-48C9-BA79-98F9BBE00051@ensieve.org>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox