Skip to content
Advertisement

Race Condition between SELECT and INSERT for multiple columns

Note: This is a question which is a follow up of this solution. You need to read the link to get context for this question. Also, this is for postgres v9.4

If we want to return multiple columns now instead of just 1 column, how can we achieve it?

Let’s take a table t:

Now this is what I want: whenever I call a method f_tag_id, I want it to return all the columns for the unique row if it exists in the table t else insert it and return all the columns.

So these are the things I tried for the f_insert_tag

Option1:

Option 2:

Option 3:

All the 3 worked by themselves:

For the other function, f_tag_id as well I tried many methods:

Option 1:

Option 2:

For both these, I got the same error:

Advertisement

Answer

The wrench in the works is SELECT f_insert_tag(tag_p_id, _tag) instead of

SELECT * FROM f_insert_tag(tag_p_id, _tag)

For Postgres 9.4

db<>fiddle here

For Postgres 9.5 or later:

db<>fiddle here

Basics here:

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