'Insert record if id is missing [duplicate]

I have this SQL query which I need to run on different databases. In some databases it's missing. In other this record is present.

INSERT INTO common.pair_aliases (pair_id, alias)
VALUES (356, 'parisrome');

Is it possible to implement a logic first to check is this record present before executing the SQL query?



Solution 1:[1]

If I understand you correctly, maybe WHERE NOT EXISTS could help you:

INSERT INTO common.pair_aliases (pair_id, alias)
SELECT R.*
FROM (VALUES (356, 'pairsrome')) R (pair_id, alias)
WHERE NOT EXISTS (SELECT 1 FROM common.pair_aliases PR WHERE PR.pair_id = R.pair_id)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Emin Mesic