HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Is there a way to set variable in UPDATE statement in PostgreSQL (plpgsql)?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqlupdatestatementwayplpgsqltherevariableset

Problem

Something like this:

DECLARE
c INTEGER;
UPDATE table SET col = (c := col + 1) WHERE id = 1;


This is wrong:

ERROR:  syntax error at or near ":="


how to do it right?

Solution

Assuming the update only affects one row:

DECLARE
c INTEGER;
UPDATE table SET col = col + 1 WHERE id = 1
  RETURNING col INTO c;


Reference.

Code Snippets

DECLARE
c INTEGER;
UPDATE table SET col = col + 1 WHERE id = 1
  RETURNING col INTO c;

Context

StackExchange Database Administrators Q#118033, answer score: 4

Revisions (0)

No revisions yet.