0

I have a table t1

create table t1 (
  id int primary key not null,
  name varchar(64),
  str2 varchar(64)
);

I want to get the row ID and update a field str2 in this row.

I tried this:

WITH inserted AS (
  insert into t1(id, name) values (38, 'www') returning *
) UPDATE t1 SET str2='aaa' WHERE id IN (SELECT id FROM inserted);
select * from t1;

I expected:

| id | name |   str2 |
|----|------|--------|
| 38 |  www |   aaa  |

But the actual result was:

| id | name |   str2 |
|----|------|--------|
| 38 |  www | (null) |

See this SQLFiddle for a reproduction scenario.

What am I doing wrong?

1
  • Are you also trying to retrieve the newly inserted id after the insert? You can achieve this with returning id Commented Jul 12, 2016 at 5:51

1 Answer 1

3

There's no point in using UPDATE to rows INSERTed in the same statement, as the INSERT could set the missing column in the first place:

insert into t1(id, name, str2) values (38, 'www', 'aaa');

Besides the pointlessness, it doesn't work, as shown in the question.

The reason is mentioned in the doc in 7.8.2. Data-Modifying Statements in WITH:

All the statements are executed with the same snapshot (see Chapter 13), so they cannot "see" one another's effects on the target tables

[...]

Trying to update the same row twice in a single statement is not supported. Only one of the modifications takes place, but it is not easy (and sometimes not possible) to reliably predict which one. This also applies to deleting a row that was already updated in the same statement: only the update is performed. Therefore you should generally avoid trying to modify a single row twice in a single statement. In particular avoid writing WITH sub-statements that could affect the same rows changed by the main statement or a sibling sub-statement. The effects of such a statement will not be predictable.

2
  • 2
    I can't modify the insert, I can only use it as a subquery of my query Commented Jul 12, 2016 at 7:34
  • 2
    @user5955758 you say you can't modify the insert but seems like you could modify the whole statement to have more ctes? Seems weird to me. Commented Jul 13, 2016 at 0:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.