4
insert into addresses(street, city, user_id)
select 
      'street1','LA', 2
where exists (select * from users where users.id = $$$$$ AND users.storeaddress='true'))

I want to insert address for a user only if the storeaddress value for him is 'true'.

I want to sql to automatically use 2 in place of $$$$$. How to do this in sql?

If I simply do user_id in place of $$$$$ I get

HINT:  There is a column named "user_id" in table "addresses", but it cannot be referenced from this part of the query.
1
  • Can you please provide table schema for the pertinent tables?
    – Erik
    Aug 27, 2015 at 14:57

1 Answer 1

5

You can use a CTE to supply the values:

with data (street, city, user_id) as (
  values ('street1','LA', 2)
)
insert into addresses(street, city, user_id)
select *
from data
where exists (select * 
              from users
              where users.id = data.user_id 
                and users.storeaddress = true);

Or alternatively a derived table:

insert into addresses(street, city, user_id)
select *
from (
   values ('street1','LA', 2)
) as data (street, city, user_id)
where exists (select * 
              from users
              where users.id = data.user_id 
                and users.storeaddress = true);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.