1

Right now, I have this table:

id|name|status (varchar)|fk_id_test (int)
-----------------------------------------
1 |ABC | X              |
2 | DX | Y              |
3 | ZZ | X              |
4 | TU | Y              |
5 | EE | Z              |

I have to insert in fk_id_test values coming from status column.

The algorithm would be something like:

switch(status)
    case 'X': `fk_ik_test` = 1
    case 'Y': `fk_ik_test` = 2
    case 'Z': `fk_ik_test` = 3
etc.

The result should be this:

Right now, I have this table:

id|name|status (varchar)|fk_id_test (int)
-----------------------------------------
1 |ABC | X              |1
2 | DX | Y              |2
3 | ZZ | X              |1
4 | TU | Y              |2
5 | EE | Z              |3

I have 5 status. This is because I will use another table (test) with the names of those status (varchar).

It's possible to do this in postgresql?

3 Answers 3

1

One method uses an update with a join:

update t
    set fk_id_test = v.fk_id_test
    from (values ('X', 1), ('Y', 2), ('Z', 3)) v(status, fk_id_test)
    where v.status = t.status;
Sign up to request clarification or add additional context in comments.

1 Comment

Wonderful and flawless. Took 1:40 min to update my 16M registries :D
1

do you need update

 update table_name
 set fk_id_test= case status when 'X' then 1
    when 'Y' then 2
    when 'Z' then 3 end

Comments

0

Are you looking for a case expression?

case status
    when 'X' then 1
    when 'Y' then 2
    when 'Z' then 3
etc.

end as fk_ik_test

3 Comments

I need to persist the data in the table, I need to create new data in this new column, The table didn't have it, now was recently created and empty of course.
That's not adviced. You could create a view instead, adding the fk_ik_test column.
I have to fill the new field

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.