HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

How to use a value from insert in conditional insert in postgres

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
insertpostgresvalueconditionalhowfromuse

Problem

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.

Solution

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);

Code Snippets

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);
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);

Context

StackExchange Database Administrators Q#112431, answer score: 5

Revisions (0)

No revisions yet.