Skip to content
Advertisement

WITH returned table behave unexpectedly when used with RETURNING in Postgresql?

I’m stumped. Why does this work fine…

But the below doesn’t – it returns an empty table. I can query the returned table sst just fine (e.g. SELECT * FROM sst), but when I try to use

I’m trying to select all the pairs in the table subtopics_results (subtopic_id and student_id) after an insertion, but keep getting nothing back, even though I do expect to have results.

I have tried inner joins, no avail.

Is this to do with the RETURNING statement?

Advertisement

Answer

That behavior is documented in “7.8.2. Data-Modifying Statements in WITH:

(…)

The sub-statements in WITH are executed concurrently with each other and with the main query. Therefore, when using data-modifying statements in WITH, the order in which the specified updates actually happen is unpredictable. All the statements are executed with the same snapshot (see Chapter 13), so they cannot “see” one another’s effects on the target tables. (…)

(…)

Maybe using UNION ALL to merge the rows returned by RETURNING and the ones already in the table before the INSERT happens can do what you want here.

Or, if you just want the inserted rows back (that’s not entirely clear to me) simply use:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement