Change more than one row in postgresql

Viewed 63

I need to change rows in my DB using 2 arrays, first stores names of rows which i need to change, second stores val. I've added the code , to understand what I want to do. Can i do it with 1 request to my DB

func update_1(){
    key := []string{"Name1", "Name2", "Name4"}
    val := []string{"1", "2", "4"}
    for i, _ := range key{
        _, err := db.Exec("UPDATE table SET val = $1 WHERE name = $2",val[i], key[i])
        if err != nil {
            errorLog.Println(err)
            return
        }
    }
}
1 Answers

You can pass the arrays into a Postgres query as parameters. Then it is a simple unnest() and update:

update t
    set val = u.val
    from unnest(:ar_names, :ar_vals) u(name, val)
    where t.name = u.name;
Related