There is a sentence MERGE
in several mature DBMS for these cases.
MERGE
is INSERT
and UPDATE
at same time.
General syntax example:
MERGE INTO TABLE_NAME USING table_reference ON (condition)
WHEN MATCHED THEN
UPDATE SET column1 = value1 [, column2 = value2 ...]
WHEN NOT MATCHED THEN
INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...
Some DBMS like MySQL has its own syntax with the same idea.
See more in Wikipedia.
If your DBMS doesn't soppurt that then you can write a Stored Procedure with the same logic.
But a stored procedure or any kind of other check in your code before insertion will make a 'lag' and the operation will become 'non-atomic'. It means that it is possible that just after your check and before insertions another transaction can make a duplicate record and you will get unexpected duplicates or excpetions. To avoid this you will have to lock the table before this operation to obtain exclusive access to the table what has a porfomance penalty because of serialization of the access.
Or you can use INSERT
with SELECT
like this:
INSERT (field1, ...) INTO table1
SELECT value1, ...
FROM DUAL -- put a name of analogue of Oracle's DUAL here
WHERE NOT EXISTS (
SELECT 1
FROM table1
WHERE key = :new_key
)
But as you understand it will not update anything.