Note that there are some explanatory texts on larger screens.

plurals
  1. POPostgresQL Stored Procs: Using a set of results in an update statement without looping through the set
    primarykey
    data
    text
    <p>I have a stored procedure in which I need to query for a set of <code>ids</code> and then use that set in an <code>UPDATE</code> statement's <code>WHERE</code> clause. I'm using <strong>PostgresQL 9.0+</strong>. I'd rather not use a loop over the set of <code>ids</code> and issue multiple <code>UPDATE</code> statements -- that's not very efficient.</p> <p>Here's a simple example:</p> <pre><code>CREATE OR REPLACE FUNCTION test_it() RETURNS VOID AS $$ DECLARE cur_time TIMESTAMP; ids a%ROWTYPE; BEGIN SELECT id FROM a INTO ids; UPDATE b SET state = 'foobar', updated_at = cur_time WHERE id IN ids; END; $$ LANGUAGE plpgsql; </code></pre> <p>This doesn't even compile.</p> <p>I've also tried <em>SELECT</em>-ing the <code>ids</code> like so...</p> <pre><code>CREATE OR REPLACE FUNCTION test_it() RETURNS VOID AS $$ DECLARE cur_time TIMESTAMP; ids a%ROWTYPE; BEGIN SELECT id FROM a INTO ids; UPDATE b SET state = 'foobar', updated_at = cur_time WHERE id IN (SELECT ids); END; $$ LANGUAGE plpgsql; </code></pre> <p>This throws an error: <em>HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.</em></p> <p>My actual stored proc is a lot more complicated because the initial query for the set of <code>ids</code> is actually a dynamic query.</p> <p>The actual error output is this (just more context...):</p> <pre><code>ERROR: operator does not exist: integer = task_responses LINE 3: WHERE id IN (SELECT task_response_ids) ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. QUERY: UPDATE task_responses SET state = state, updated_at = cur_time, rejected_at = cur_time WHERE id IN (SELECT task_response_ids) CONTEXT: PL/pgSQL function "reject_submissions_with_comment" line 38 at SQL statement </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload