0

Lets say that I have a simple SQL script:

UPDATE my_table
SET data = new_data
WHERE my_table.data IS NULL;

I would like to print which id's that where updated in the UPDATE command. So something like this functionality-wise:

UPDATE my_table
SET data = new_data, RAISE NOTICE 'Updated %', my_table.id
WHERE my_table.data IS NULL;

Is this possible? I am using PostgreSQL.

Arenlind
  • 53
  • 5

3 Answers3

2

Ok, I came up with something like this.

DO language plpgsql $$
DECLARE _id bigint;
BEGIN
    FOR _id IN
    WITH up AS (
      UPDATE my_table
        SET data = new_data
        WHERE data IS NULL
        RETURNING id)
    SELECT id from up
    LOOP
      RAISE NOTICE 'Updated %', _id;
    END LOOP;
END
$$;

It is a bit clumsy, but should work for you.

At first, RAISE NOTICE has to be wrapped like explained here. I found no way how to store multiple rows (...RETURNING id) into variables, which might not be possible with current versions. That's why I let a select follow the update, which itself feeds the RAISE you require.

Community
  • 1
  • 1
maxik
  • 1,053
  • 13
  • 34
1

You can return use the RETURNING clause of the UPDATE statement to return values from each updated row. From the documentation's example:

UPDATE weather SET temp_lo = temp_lo+1, temp_hi = temp_lo+15, prcp = DEFAULT
  WHERE city = 'San Francisco' AND date = '2003-07-03'
  RETURNING temp_lo, temp_hi, prcp;

This will return the updated temperatures.

In your case you could try:

UPDATE my_table
 SET data = new_data
 WHERE my_table.data IS NULL
 RETURNING id;
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
0

If you want to return the updated rows ID then Try like this,

For Update:

 UPDATE my_table SET col2 = val2 WHERE col1 = val1 RETURNING ID; 

For Insert:

INSERT INTO my_table (col2) values ( val2 ) RETURNING ID;

StackUser
  • 5,370
  • 2
  • 24
  • 44