0

I need to do update, but for each row different value.

I have sql like:

select c.id as client_id, c.name as c_name, st.id as st_id, st.name as st_name, c.default_store_type_id 
from client c
join store_type st on c.id = st.client_id

and now I need for each client do update:

UPDATE client c SET c.defaultStoreTypeId = st.id

I am trying but with as:

with cte (client_id, c_name, st_id, st_name)
    as (
        select c.id as client_id, c.name as c_name, st.id as st_id, st.name as st_name from client c
        join store_type st on c.id = st.client_id
        where c.id not in (9, 12)
        order by c.id
    ) 

But no idea here how to prepare UPDATE.

2 Answers 2

1

You can use Postgres update ... set ... from ... where ... syntax:

update client c
set defaultstoretypeid = s.id
from store_type s
where c.id = s.client_id;

Note: Postgres does not accept table prefixes in the set clause.

Demo on DB Fiddle

Sign up to request clarification or add additional context in comments.

Comments

1

You can use a FROM clause:

UPDATE client c
    SET defaultStoreTypeId = st.id
    FROM store_type st 
    WHERE c.id = st.client_id;

2 Comments

hmm but then Ive an error: SQL Error [42703]: ERROR: column "c" of relation "client" does not exist
@Baku . . . Don't use an alias in the set. I missed that your expression had this.

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.