I'd like to insert new row into tableA if doesn't exist row with the given id_client (in PostgreSQL):
INSERT INTO tableA(id_client, opr_wpr, data_wpr)
VALUES((SELECT id_client FROM tableB WHERE id = 272), 212121, now());
How can I do that?
I'd like to insert new row into tableA if doesn't exist row with the given id_client (in PostgreSQL):
INSERT INTO tableA(id_client, opr_wpr, data_wpr)
VALUES((SELECT id_client FROM tableB WHERE id = 272), 212121, now());
How can I do that?
Use a SELECT as the source of the INSERT:
with data as (
SELECT id_client, 212121 as opr_wpr, now() as data_wpr
FROM tableB
WHERE id = 272
)
INSERT INTO tablea(id_client, opr_wpr, data_wpr)
SELECT *
FROM data
WHERE not exists (select *
from tablea
where id_client in (select id_client
from data));
The common table expression is used so that the source condition only needs to be provided once.
Alternatively if you have a unique constraint on tablea.id_client
, then you can simply do:
INSERT INTO tablea(id_client, opr_wpr, data_wpr)
SELECT id_client, 212121, now()
FROM tableB
WHERE id = 272
on conflict (id_client) do nothing;
Like this:
INSERT INTO tableA(id_client, opr_wpr, data_wpr)
SELECT b.id_client, 212121, now()
FROM
tableB b
LEFT JOIN tableA a
ON b.id_client = a.id_client
WHERE b.id = 272 AND a.id_client is null;
The select query will only return one row when there is:
When there is no row, the left join will return a null in tableA.id_client. As soon as a row is inserted into tableA for that id_client, the left join will cease to return a null and return the related row instead. It is a condition of the WHERE that the a.id_client be null, which it no longer is. This causes the SELECT statement to return 0 rows instead, meaning nothing is inserted
INSERT INTO tableA(id_client, opr_wpr, data_wpr)
VALUES((SELECT id_client FROM tableB WHERE id != null), 212121, now());