SQL. i have two tables residents (primary key rid) and dependents (primary key did). dependents is connected to residents through rid. I want to insert rows into dependents table only if the rid in the insert statement matches with any of the rid in the residents table. i tried the code below, but there is some error with the where clause.
x
insert into
dependents(rid, name, did, phone)
values
(1, 'george', 156, 8134563255)
where
exists(
select
rid
from
residents
where
residents.rid = dependents.rid
);
Advertisement
Answer
To my mind, it doesn’t make sense to insert a value that already exists, so I think that you might want actually want update
:
update dependents
set name = 'george',
did = 156,
phone = 8134563255
where rid = 1;
If you want insert
, then use insert . . . select
:
insert into dependents (rid, name, did, phone)
select 1, 'george', 156, 8134563255
from residents r
where r.id = 1;
If you want to insert all residents, then:
insert into dependents (rid, name, did, phone)
select r.id, 'george', 156, 8134563255
from residents r;